Dan*_*ane 24 t-sql sql-server random
如何根据所有候选行的应用权重在T-SQL中随机选择一个表行?
例如,我在一个表中有一组行加权为50,25和25(最多加100但不需要),我想随机选择其中一行,其统计结果相当于各自的重量.
Mat*_*lie 15
戴恩的答案包括以引入平方定律的方式自我加入.(n*n/2)
连接后的行,表中有n行.
更理想的是能够只解析一次表.
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), 0)
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
Run Code Online (Sandbox Code Playgroud)
这将通过表格,设置@id
为每个记录的id
值,同时减少@weight
点数.最终,@weight_point
意志将消极.这意味着SUM
所有先前权重中的权重大于随机选择的目标值.这是我们想要的记录,所以从那时起我们设置@id
为自己(忽略表中的任何ID).
这只会在表中运行一次,但即使所选值是第一个记录,也必须遍历整个表.因为平均位置是表格的一半(如果按递增权重排序则更少)写一个循环可能会更快......(特别是如果权重是共同的组):
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
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), 0)
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
Run Code Online (Sandbox Code Playgroud)
您只需要对所有候选行的权重求和,然后在该总和中选择一个随机点,然后选择与该选定点协调的记录(每个记录逐渐携带与其累加的权重总和).
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 = ROUND(((@weight_sum - 1) * RAND() + 1), 0)
SELECT TOP 1 @id = t1.id
FROM @table t1, @table t2
WHERE t1.id >= t2.id
GROUP BY t1.id
HAVING SUM(t2.weight) >= @weight_point
ORDER BY t1.id
SELECT @id
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7585 次 |
最近记录: |