假设有一个包含2列的SQL Server表:ID, Value
示例数据如下所示:
ID value
------------------
1 30
1 30
2 50
2 50
3 50
当我运行此查询时:
select ID, NEWID(), value
from table1
order by ID
结果如下:
1 30 E152AD19-9920-4567-87FF-C4822FD9E485
1 30 54F28C58-ABA9-4DFB-9A80-CE9C4C390CBB
2 50 ........
2 50 ........
3 50 4E5A9E26-FEEC-4CC7-9AC5-96747053B6B2
但我想要的是:有多少ID记录取决于(值/ 30的总和)的结果,例如ID 2,它的值的总和是50 + 50 = 100,而100/30 = 3,所以ID 2将在查询结果中显示三次
我想要的最终结果是这样的:
1 E152AD19-9920-4567-87FF-C4822FD9E485
1 54F28C58-ABA9-4DFB-9A80-CE9C4C390CBB
2 4E5A9E26-FEEC-4CC7-9AC5-96747053B6B2
2 ....
2 ....
3 D861563E-E01A-4198-9E92-7BEB4678E5D1
请注意2的ID显示三次,等待你的帮助,谢谢。
答案 0 :(得分:1)
像
这样的东西CREATE TABLE Table1
([ID] int, [value] int)
;
INSERT INTO Table1
([ID], [value])
VALUES
(1, 30),
(1, 30),
(2, 50),
(2, 50),
(3, 50)
;
;WITH SummedVals AS (
SELECT ID,
SUM(value) / 30 Cnt
FROM Table1
GROUP BY ID
)
, Vals AS (
SELECT ID,
Cnt - 1 Cnt
FROM SummedVals
UNION ALL
SELECT ID,
Cnt - 1 Cnt
FROM Vals
WHERE Cnt > 0
)
SELECT ID,
NEWID()
FROM Vals
ORDER BY 1