我有一个SQL表,如下所示:
Id Quantity
1 24.857
2 24.84
3 24.881
4 24.823
我需要选择数量的累积总和,直到达到指定值 - 比方说50。 所以使用上面的表格,我需要查询返回前3行。 (前两行的数量总和不会达到50,所以我也需要第三行。)
现在我有下面的代码,它虽然接近但不太正确。此查询的结果仅返回表的前两行,这是不够的。
DECLARE @point INT = 50;
WITH x(Id, Quantity, RowNum, TotalQuantity) AS
(
SELECT
id, quantity, ROW_NUMBER() OVER (ORDER BY id),
SUM(quantity) OVER (ORDER BY id RANGE UNBOUNDED PRECEDING)
FROM inventory
)
SELECT x.Id, x.RowNum, x.Quantity, x.TotalQuantity
FROM x
WHERE x.TotalQuantity <= @point
ORDER BY x.Id
此查询会产生以下结果:
Id RowNum Quantity TotalQuantity
1 1 24.857 24.857
2 2 24.84 49.697
我觉得好像我在这里需要一个WHILE
循环,我试图无济于事。
非常感谢任何帮助,谢谢。
答案 0 :(得分:1)
当总数量为&gt; = @point时,您可以再使用一个cte来获取第一行。然后加入现有的cte。
WITH x(Id, Quantity, RowNum, TotalQuantity) AS
(
SELECT
id, quantity, ROW_NUMBER() OVER (ORDER BY id),
SUM(quantity) OVER (ORDER BY id RANGE UNBOUNDED PRECEDING)
FROM inventory
)
, y as (select min(rownum) as minrownum from x where totalquantity >= @point)
SELECT x.Id, x.RowNum, x.Quantity, x.TotalQuantity
FROM x
JOIN y on x.rownum <= y.minrownum
ORDER BY x.Id
答案 1 :(得分:1)
您可以使用LAG查看前一行。
WITH x(Id, Quantity, RowNum, TotalQuantity, TotalQuantityPrior) AS
(
SELECT
id, quantity, ROW_NUMBER() OVER (ORDER BY id),
SUM(quantity) OVER (ORDER BY id RANGE UNBOUNDED PRECEDING) AS TotalQuantity,
LAG(TotalQuantity,1,0) OVER (ORDER BY id) AS TotalQuantityPrior
FROM inventory
)
SELECT x.Id, x.RowNum, x.Quantity, x.TotalQuantity
FROM x
WHERE x.TotalQuantityPrior <= @point
ORDER BY x.Id
我默认使用0 - 如果您可以将0作为@point,或者根据您的业务规则可能有其他内容,您可能需要-1。