Weighted Random Numbers

Apr 11, 2007

Hi there... I've got an interesting one, that I can't seem to get my head around. Maybe some legend out there might be able to give me a hand...

I'm looking for a way to produce a weighted set of random numbers. I'm doing some work for a client at the moment, and they want to issue 3 random "reward cards" to their members at certain times. These are a bit like discount vouchers etc. The problem is some cards have need to have a higher frequency than the others. I guess a similar problem to baseball cards, you buy a pack of cards, you get mostly common cards, but every now and then, you get a rare card.

Here is the table setup:
CREATE TABLE [dbo].[Cards](
[CardID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Cards_CardID] DEFAULT (newid()),
[CardName] [nvarchar](50) NOT NULL,
[InsertRatio] [float] NULL,
CONSTRAINT [PK_Cards] PRIMARY KEY CLUSTERED
(
[CardID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 1', NULL) /* Null implies the card is a common card */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 2', NULL) /* Null implies the card is a common card */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 3', NULL) /* Null implies the card is a common card */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 4', NULL) /* Null implies the card is a common card */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 5', NULL) /* Null implies the card is a common card */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 6', NULL) /* Null implies the card is a common card */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 7', NULL) /* Null implies the card is a common card */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 8', NULL) /* Null implies the card is a common card */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 9', NULL) /* Null implies the card is a common card */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Rare 1', 0.02) /* 1:50 ratio */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Rare 2', 0.02) /* 1:50 ratio */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Rare 3', 0.02) /* 1:50 ratio */
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Very Rare 1', 0.005) /* 1:200 ratio */



So what I need to do, is have a Stored Proc that I can execute and it returns back 3 random rows. Now in that single run, a card can't be duplicated.

Notice the Insert Ratio column? This has the ratio of the probability, eg a 1:50 insert ratio is equal to 0.02. For the common cards, a NULL value indicates it is a common.

Eventually, this table would have about 1000 rows in it, and about 200 of those would have various ratios (eg 1:50, 1:200, 1:1000, 1:8000 etc)

Any ideas or comments?

Thanks in advance.

Leddo
Brisbane, Australia

View 6 Replies


ADVERTISEMENT

I Need To Update A Table With Random Numbers Or Sequential Numbers

Mar 11, 2008



I have a table with a column ID of ContentID. The ID in that column is all NULLs. I need a way to change those nulls to a number. It does not matter what type of number it is as long as they are different. Can someone point me somewhere with a piece of T-SQL that I could use to do that. There are over 24000 rows so cursor change will not be very efficient.

Thanks for any help

View 6 Replies View Related

Random Numbers.

Jun 22, 2001

I am trying to get random numbers to have a unique value for different processes, then I can identify each process. What happens is that I use rand() function without seed, so I got my random numbers, but after shutting down SQLServer and try to get again another random number after booting up, the same series of random numbers is given again and again. So if anyone knows how I can get unique values,even though reseting the server, and using random function or any other method which automatically provides unique values,I'll really appreciate it if you let me know it.

This is the function: select rand()

Alberto.

View 2 Replies View Related

Random Numbers

Mar 19, 2008

Hi,

I have an int column that i want to have random numbers inserted into it.
How can I create random integer numbers to insert into my column?

Thanks

Whisky-my beloved dog who died suddenly on the 29/06/06-I miss u so much.

View 3 Replies View Related

Generate Random Numbers

Dec 12, 2006

Hi, how do I use the Rand Function to generate a Random integer value between 1 and 20. Any help will be appreciated.
 Thanks

View 1 Replies View Related

Update With Random Numbers

Jan 2, 2008

I have a table with a field called "host" and I want to replace the value of this column in each row with 'Host' followed by a random number. I have created the below function to do this:
DECLARE @Random varchar;
SELECT @Random = CONVERT(int, (20+1)*RAND())+ 1;
UPDATE AnalogLines Set [Host Name] = 'Host' + @Random
 
This sorta works... the problem is, the random number is determine and then the SAME random  number is applied to each row. I need a different random number for every row. Any ideas?

View 3 Replies View Related

Create Random Numbers Within A Range?

Dec 27, 2013

s it possible to create random numbers within a range like : .28 to .57 ?

UPDATE Nop_ProductVariant
SET percent = RAND() .28 to .57

So the percent field would look like :

ProdID percent
1001 .38
1002 .29
1003 .40
etc . .

all rows having a different value

View 12 Replies View Related

Inputting Random Numbers To Table Column From Web Form

Feb 28, 2007

I'm grappling with this issue which I thought was basic VB programming; I'm trying to insert a random number (between 100 and 999) into a SQL table column (=Status_ID). This is input as part of a user submitting helpdesk requests via a APS.Net Web Form. The 'Status_ID' field is obviously not visible to the user but will help reference this Helpdesk request on the database.Here is the code:Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click        If Page.IsValid Then            ' Define data objects            Dim conn As SqlConnection            Dim comm As SqlCommand            ' Read the connection string from web.config            Dim connectionString As String = _            ConfigurationManager.ConnectionStrings("ITNet_Students").ConnectionString            ' Initialize connection            conn = New SqlConnection(connectionString)            ' Create command            comm = New SqlCommand( _            "INSERT INTO HelpDesk (First_Name, Last_Name, StudentID, PersonalEmail," & _            "CategoryID, SubjectID, Description, StatusID) " & _            "VALUES (@First_Name, @Last_Name, @StudentID, @PersonalEmail, " & _            "@CategoryID, @SubjectID, @Description, @StatusID)", conn)            ' Use randomize            Randomize()            Dim randomvalue As Integer            ' Generate random value between 999 and 100.            randomvalue = Int((900 * Rnd()) + 100)            ' Add command parameters            comm.Parameters.Add("@First_Name", System.Data.SqlDbType.NVarChar, 50)            comm.Parameters("@First_Name").Value = fnameTextBox.Text            .            .            .            comm.Parameters.Add("@StatusID", System.Data.SqlDbType.Int)            comm.Parameters("@StatusID").Value = randomvalue            'Enclose database code in Try-Catch-Finally            Try                ' Open connection                conn.Open()                ' Execute the command                comm.ExecuteNonQuery()                ' Reload page if the query executed successfully                Response.Redirect("HelpDesk.aspx")            Catch                ' Display error message                dbErrorMessage.Text = _                    "Error submitting the help desk request! Please try again later, and/or change the entered data!"            Finally                'close connection                conn.Close()            End Try        End If    End Sub----------------------------------------------------------------------------------------------------------------------I keep getting the error message under 'Catch'  and the page 'HelpDesk.aspx' is not reloading; the 'comm.ExecuteNonQuery()' is not executing.Can anyone spot any inconsistencies in the declaration of the 'randomvalue' variable?P.S: this code works fine if you replace 'randomvalue' with any integer in 'comm.Parameters("@StatusID").Value = randomvalue' 

View 2 Replies View Related

Efficiently Creating Random Numbers In Very Large Table

Jan 19, 2007

Hello,

I need to sample data in a very large table in SQL Server 2000 (a gazillion rows of Performance Monitor statitics).

I'd like to take the top 5%, for instance, based upon a column containing random numbers.

Can anyone suggest a highly efficient method of populating a column with random numbers.

Thanks in advance.

Rod

View 10 Replies View Related

SQL Server 2008 :: CAST (INT AS DATETIME) - Random Numbers

May 20, 2015

While trying to solve a SQL challenge I found myself trying to understand what is happening when you CAST a INT to date time.

Trying to understand the results. Here are some random numbers and Castings. My question is why do they produce the datetimes they do?

SELECT CAST((1.1) AS DATETIME)
SELECT CAST((200) AS DATETIME)
SELECT CAST((15) AS DATETIME)
SELECT CAST((99.99999) AS DATETIME)

View 9 Replies View Related

Formatting Numbers In A Mixed Column (numbers In Some Cells Strings In Other Cells) In Excel As Numbers

Feb 1, 2007

I have a report with a column which contains either a string such as "N/A" or a number such as 12. A user exports the report to Excel. In Excel the numbers are formatted as text.

I already tried to set the value as CDbl which returns error for the cells containing a string.

The requirement is to export the column to Excel with the numbers formatted as numbers and the strings such as "N/A' in the same column as string.

Any suggestions?



View 1 Replies View Related

Returning Random Records And NOT Similar (random Questions)

Jul 20, 2005

Hi,I need to extract randomly 5 records from the table "Questions". Now I useSELECT TOP 5 FROM Questions ORDERBY NEWID()And it works. The problem is that I need an additional thing: if SQLextracts record with ID=4, then it should not extract record with ID=9,because they are similar. I mean, I'd like something to tell SQL that if itextracts some questions, then it SHOULD NOT extract other ones.How can I do it?Thanks!Luke

View 1 Replies View Related

Weighted Sum?

Aug 31, 2007

I need to run some statistics on a dataset. I've never used SUM or COUNT(*) before, but I'm pretty sure I need them for this. If this is my table:

GROUP nvarchar(10) QTY tinyint TYPE smallint VALUE decimal(3,2)
g1 q1 t1 v1
g1 q1 t2 v2
g2 q2 t1 v3
g2 q2 t2 v4
g3 q3 t1 v5
g3 q3 t2 v6
g4 q4 t3 v7

and I need this output
v1 * q1 / (q1 + q2 + q3 + q4) + v3 * q2 / (q1 + q2 + q3 + q4) + v5 * q3 / (q1 + q2 + q3 + q4)
v2 * q1 / (q1 + q2 + q3 + q4) + v4 * q2 / (q1 + q2 + q3 + q4) + v6 * q3 / (q1 + q2 + q3 + q4)
v7 * q4 / (q1 + q2 + q3 + q4)

how can I query this? I think that I have to group by TYPE, but other than that I don't know how to do this. Thanks for your help.

View 15 Replies View Related

Weighted Search??

Oct 5, 2006

I have to perform a weighted search.  I have 2 criteria and each will be weighted on a 100 sum(e.g 25/75, 50/50).  I am just wondering if there is an easy way to encompass a weighted value on SELECTS.  Sorry if this is a dumb question. Thanks,Kyle 

View 1 Replies View Related

Weighted Average

Nov 4, 2005

Does anyone know if it's possible to calculate weighted averages on report level, based on 2 items in the report?

View 6 Replies View Related

Weighted Search On Fulltext Index

Aug 20, 2007

SQL Server 2005:
Anyone know how best to rewrite this SQL string to perform a weighted search on my table?
here's my code:
SQL="SELECT RecipeName FROM recipeList WHERE FREETEXT(*,'ISABOUT " & ing01 & " WEIGHT (.1) or " & ing02 & " WEIGHT (.2) or " & ing03 & " WEIGHT (.3) or " & ing04 & " WEIGHT (.4) or " & ing05 & " WEIGHT (.5)')"
the idea is to get a list of recipes most pertinant to the ingredients entered.
table 'recipeList' contains the ingredients in several columns. so column 2 might say '5oz of flour', column 2 - '2oz butter' etc.

at the moment it returns the correct recipes but not in the right order.
If I use 'CONTAINS' it returns nothing.
hope that's not too vague!

View 10 Replies View Related

Script For SQL Agent Weighted Job Duration

Jul 20, 2005

Hi,Does anyone know of a script that will give "weighted job duration"?I want to use it, to identify which jobs are hogging the CPU. That isfor a given server, list the sql agent jobs ordered by:(avg job duration in minutes) times (avg num of times job runs in agiven day).

View 2 Replies View Related

Join To Select A 'weighted' Column

Mar 28, 2006

Perhaps is just brain drain but i cannot seem find an efficient query to join two tables (inv and supplier) such that an inv item can have multiple suppliers and i would like to choose the prefered supplier based on the current 'weight' column.

declare @inv table (item varchar(50), supplierid int)

declare @supplier table (supplierid int, weight int)

set nocount on

insert into @inv values ('item1', 1)

insert into @inv values ('item1', 2)

insert into @inv values ('item2', 2)

insert into @inv values ('item2', 3)

insert into @supplier values(1, 30)

insert into @supplier values(2, 20)

insert into @supplier values(3, 10)

-- the query should return the item and the supplierid associated to the lowest weight
-- item1 -> supplier 2
-- item2 -> supplier 3

select item, ps2.supplierid from @supplier ps2 join

(select item, min(ps.weight)'weight'

from @inv inv join @supplier ps on inv.supplierid=ps.supplierid

group by item) iw on ps2.weight=iw.weight

Is there a better alternative to this?

Thanks in advance,

Mike

View 3 Replies View Related

Prediction Query For A Weighted Clustering Model

Dec 12, 2006

I have a question about writing a prediction query against a clustering model that has the same column added more than once.

Per Jamie, I can accomplish some crude weighting by adding a column to my model multiple times. See this post for an explnation... Now that I have that worked out, I was wondering how my DM query would look? If I have Input_A1, Input_A2 , & Input_A3 all being source from the same column in my structure do I have to reference all three when writing my prediction query?

View 1 Replies View Related

URGENT - Random 10 From Random 20 (2 Tbls)

Oct 14, 2004

I'm using ASP and SQL Serv 2000. What I need to get from 2 tables (company & customers) is random 10 customers from random 20 comp.
Anyone got an idea how to do this??? I've spent 2 days trying to get stored proc. or T-SQL to work, but nothing good came out of it. I can get 1 comp and 10 cust, but not a grouped list of 20 comp. w/ 10 cust. each.

Help is greatly appreciated.

View 1 Replies View Related

Power Pivot :: Formula For Row Wise Weighted Average

Apr 22, 2015

I have a table in `PowerPivot` which contains the logged data of a traffic control camera mounted on a road. This table is filled the velocity and the number of vehicles that pass this camera during a specific time(e.g. 14:10 - 15:25). Now I want to know that how can I get the average velocity of cars for an specific hour and list them in a separate table with 24 rows(hour 0 - 23) where the second column of each row is the weighted average velocity of that hour?

A sample of my stat_table data is given below:
 
count    vel          hour  
-----    --------   ----  
133    96.00237    15  
117    91.45705    21  
81      81.90521    6  
2        84.29946    21  
4        77.7841      18  
1        140.8766    17  

[Code] ....

In a separate `PowerPivot` table I have 24 rows and 2 columns(column1 is for hours and column 2 for weighted averages) and when I enter my formula, the whole rows get updated with the same number. My formula is:   

=sumX(FILTER(stat_table, stat_table[hour]=[hour]), stat_table[count] * stat_table[vel])/sumX(FILTER(stat_table, stat_table[hour]=[hour]), stat_table[count])

View 3 Replies View Related

Query Analyzer Shows Negative Numbers As Positive Numbers

Jul 20, 2005

Why does M$ Query Analyzer display all numbers as positive, no matterwhether they are truly positive or negative ?I am having to cast each column to varchar to find out if there areany negative numbers being hidden from me :(I tried checking Tools/Options/Connections/Use Regional Settings bothon and off, stopping and restarting M$ Query Analyer in betwixt, butno improvement.Am I missing some other option somewhere ?

View 7 Replies View Related

Generate List Of All Numbers (numbers Not In Use)

Feb 21, 2007

I have an 'ID' column. I'm up to about ID number 40000, but not all are in use, so ID 4354 might not be in any row. I want a list of all numbers which aren't in use. I want to write something like this:

select [numbers from 0 to 40000] where <number> not in (select distinct id from mytable)


but don't know how. Any clues?

View 1 Replies View Related

Dataflow To Excel - Convert Numbers Stored As Text To Numbers Excel Cell Error

Mar 27, 2007

I'm trying to write data to excel from an ssis component to a excel destination.

Even thought I'm writing numerics, every cell gets this error with a green tag:

Convert numbers stored as text to numbers

Excel Cells were all pre-formated to accounting 2 decimal, and if i manually type the exact data Im sending it formats just fine.

I'm hearing this a common problem -

On another project I was able to find a workaround for the web based version of excel, by writing this to the top of the file:

<style>.text { mso-number-format:@; } </style>

is there anything I can pre-set in excel (cells are already formated) or write to my file so that numerics are seen as numerics and not text.

Maybe some setting in my write drivers - using sql servers excel destination.


So close.. Thanks for any help or information.

View 1 Replies View Related

Minimizing Penalty (weighted Sum Of False Positives Plus False Negatives)

May 25, 2006

I am using Naive Bayes, Decision Trees, and Neural Net (SSAS 2005) to predict which of two states each record belongs to.

How can I enforce a different penalty for a false positive versus a false negative ?  (I am assuming that in some sense the mining algorithms can then minimize the total penalty).

View 5 Replies View Related

Random Row

Jul 20, 2005

Hi there.I need to fetch ONE random row from many. How can i get it? I try toexecute "SELECT field.table FROM table ORDER by RAND()" no effect.Thank you.

View 1 Replies View Related

Select Random Row In Sql

Apr 11, 2007

Hi,
i wanna fetch random data using sql query. is there any query that returns random row? Please help me.. i found some but they didnt work..

View 8 Replies View Related

How To Do A Random Select

Nov 10, 2000

Hy,
I nead to make a stored procedure in order to add a random record set.
This record set is used to write in an ASP page a list which is automatically modified everytime we reload the page.

Thanks !

View 1 Replies View Related

Random Records

Nov 16, 1999

Hi,

I'm trying to use the following query to select two random records from my database. Do you have any ideas of why the recrand field will not change? I am using MS Sql server 7.. Please email mark@dtdesign.com ..Cheers Mark

SELECT TOP 2 mytable.id AS RECID, RAND(mytable.id) AS recrand
FROM mytable
ORDER BY recrand

View 3 Replies View Related

DTS Bug? (or Random Feature?)

Jul 16, 1999

Has anyone noticed that if you created DTS package and try to
change connection properties (i.e. change DSN or redirect
DTS to different server or Database), as soon you click OK
it does not save new password and hence does not work
anymore. In my case to move Database from Development to
Production server I would have to recreate all DTS packages.
Is there any way around it?

Any ideas greatly appreciated.

View 1 Replies View Related

Random Values

Dec 24, 2001

Is there a way to write an SQL statement to choose random values from a particular select statement..for example:
select * from address
I was thinking, if there was a way to use an include statement for it like:
select * from address where id IN ('generates some random values')

thanks in advance

View 2 Replies View Related

Last Day In A Random Month

Mar 7, 2006

So i've got to generate these queries that go from the first of a one month to the last day of a month. the user provides the starting and ending months.

What I was wondering was is there an easy way to set the last day of the month in sql without having to go in and hard code which months end on the 30 and which ones end on the 31.

View 2 Replies View Related

Random Values In MS SQL,

Jan 1, 2005

Hello guys , I am new here,

Well, I am moving my greetings script from MS Access to MS SQL, here is what I was using in MS Access.

See this screenshot: Click Here
Well, I've imported the data from access database, but I don't know how to do the AutoNumber in MS SQL,

Also I don't know how can I add that Random thing *See the arrow in the screenshot*

Thanks in advance

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved