从表中选择行,使其列的计算值之和小于给定限制

时间:2013-11-20 16:52:53

标签: sql sql-server

我有一个表myTable,结构如下:

id: int PRIMARY KEY
number: int

我想在以下条件下从myTable中随机选择3行:

  1. 最多应选择三行
  2. 我们应该选择ID和计算为0,3*RAND()*number的值转换为INT。计算列的别名为randomValue
  3. 结果中只应包含randomValue>0的行
  4. randomValues的总和应该小于给定的阈值,比如60。
  5. 到目前为止,我写过:

    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,我正在测试解决方案:

    enter image description here

1 个答案:

答案 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)