我有一个表myTable,结构如下:
id: int PRIMARY KEY
number: int
我想在以下条件下从myTable中随机选择3行:
0,3*RAND()*number
的值转换为INT
。计算列的别名为randomValue
randomValue>0
的行randomValues
的总和应该小于给定的阈值,比如60。到目前为止,我写过:
SELECT TOP 3 id,randomValue
FROM(
SELECT id, CONVERT(INT,(0.3*RAND()*number)) AS randomValue
FROM myTable
WHERE number>0
) AS D
WHERE randomValue>0
ORDER BY NEWID()
上面的代码最多选择3个随机行,其中randomValue大于零。但是,我不知道如何满足条件4,即如何在所选行中实现randomValues的总和小于60.
这是myTable,我正在测试解决方案:
答案 0 :(得分:0)
WITH
random_values AS (
SELECT
id,
CONVERT(INT,(0.3*RAND()*number)) AS randomValue
FROM myTable
WHERE number>0
),
valid_sets AS (
SELECT
t1.id id1,
t2.id id2,
t3.id id3
FROM random_values t1
INNER JOIN random_values t2 ON (t2.id > t1.id)
INNER JOIN random_values t3 ON (t3.id > t2.id)
WHERE t1.randomValue + t2.randomValue + t3.randomValue < 60
)
SELECT c.id,c.number
FROM (SELECT TOP 1 * FROM valid_sets ORDER BY NEWID()) a
UNPIVOT(id FOR n IN (id1,id2,id3)) b
INNER JOIN myTable c ON (b.id = c.id)