A resposta de Dane inclui uma autojunção de uma maneira que introduz uma lei quadrada.
(n*n/2)
linhas após a junção onde há n linhas na tabela. O que seria mais ideal é poder analisar a tabela apenas uma vez.
DECLARE @id int, @weight_sum int, @weight_point int
DECLARE @table TABLE (id int, weight int)
INSERT INTO @table(id, weight) VALUES(1, 50)
INSERT INTO @table(id, weight) VALUES(2, 25)
INSERT INTO @table(id, weight) VALUES(3, 25)
SELECT @weight_sum = SUM(weight)
FROM @table
SELECT @weight_point = FLOOR(((@weight_sum - 1) * RAND() + 1))
SELECT
@id = CASE WHEN @weight_point < 0 THEN @id ELSE [table].id END,
@weight_point = @weight_point - [table].weight
FROM
@table [table]
ORDER BY
[table].Weight DESC
Isso passará pela tabela, definindo
@id
ao id
de cada registro valor enquanto ao mesmo tempo decrementa @weight
ponto. Eventualmente, o @weight_point
ficará negativo. Isso significa que a SUM
de todos os pesos anteriores é maior que o valor alvo escolhido aleatoriamente. Este é o registro que queremos, então, a partir desse ponto, definimos @id
para si mesmo (ignorando quaisquer IDs na tabela). Isso percorre a tabela apenas uma vez, mas precisa percorrer a tabela inteira, mesmo que o valor escolhido seja o primeiro registro. Como a posição média está na metade da tabela (e menos se ordenada por peso crescente), escrever um loop pode ser mais rápido ... (Especialmente se os pesos estiverem em grupos comuns):
DECLARE @id int, @weight_sum int, @weight_point int, @next_weight int, @row_count int
DECLARE @table TABLE (id int, weight int)
INSERT INTO @table(id, weight) VALUES(1, 50)
INSERT INTO @table(id, weight) VALUES(2, 25)
INSERT INTO @table(id, weight) VALUES(3, 25)
SELECT @weight_sum = SUM(weight)
FROM @table
SELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0)
SELECT @next_weight = MAX(weight) FROM @table
SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight
SET @weight_point = @weight_point - (@next_weight * @row_count)
WHILE (@weight_point > 0)
BEGIN
SELECT @next_weight = MAX(weight) FROM @table WHERE weight < @next_weight
SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight
SET @weight_point = @weight_point - (@next_weight * @row_count)
END
-- # Once the @weight_point is less than 0, we know that the randomly chosen record
-- # is in the group of records WHERE [table].weight = @next_weight
SELECT @row_count = FLOOR(((@row_count - 1) * RAND() + 1))
SELECT
@id = CASE WHEN @row_count < 0 THEN @id ELSE [table].id END,
@row_count = @row_count - 1
FROM
@table [table]
WHERE
[table].weight = @next_weight
ORDER BY
[table].Weight DESC