I have the following table:
DECLARE @TicketHolder TABLE
(
[Name] VARCHAR(100),
Tickets DECIMAL(18, 8)
);
With some test values:
INSERT INTO @TicketHolder ([Name], Tickets)
SELECT 'Bob', 10.37
UNION ALL
SELECT 'Lisa', 1
UNION ALL
SELECT 'Robbie', 150.981
UNION ALL
SELECT 'Cathy', 97.888531;
260.239531 tickets have been bought. Bob owns ~58% of the tickets, Cathy ~38%, and so on:
SELECT [Name], Tickets / (SELECT SUM(Tickets) AS WinProb
FROM @TicketHolder) WinProb FROM @TicketHolder
Now, I need to choose one and only one random winner (using RAND() is good enough) based on how many tickets each person owns. There can be millions of rows, so looping is out of the question. How can a winner be drawn using T-SQL?
This query would find a random number based on the total number of tickets:
You can combine it with a running sum query to find the owner of the block in which the random number was drawn:
Example at SE Data. On SE Data, it always selects the same winner, probably because they seed
rand()in a fixed way. If I run it locally, it works fine.