DECLARE @TotalMaxQty int
SET @TotalMaxQty = 1000
SELECT
PKId
,Qty
FROM dbo.Sales
PKId Qty
____ _____
1 100
2 200
3 750
4 200
...
I have to get 1, 2, 3 records because of SUM(Qty) <= @TotalMaxQty (record 3 should be included partially with Qty = 700).
Thank you.
You can use a recursive CTE to calculate the running sum.
Edit: A version that stores the ordered sales in a table variable with
rnas a primary key. My tests shows much improved performance.