How to query a cumulative sum up to a specific value in SQL

Viewed 953

I have a SQL table which looks like this:

Id  Quantity
1   24.857    
2   24.84
3   24.881
4   24.823

I need to select a cumulative sum of the quantity until a specified value is reached - let's say 50. So with the above table, I would need the query to return the first 3 rows. (The sum of the quantity in the first two rows does not reach 50, so I need the third row as well).

Now I have the below code which is close but not quite right. The result of this query returns only the first two rows of the table which isn't sufficient.

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

This query results in the following:

Id  RowNum  Quantity   TotalQuantity
1   1       24.857     24.857
2   2       24.84      49.697

I feel as though I need a WHILE loop in here somewhere which I have tried to no avail.

Any help is greatly appreciated, thanks.

2 Answers
Related