-- emulation of demo date
DECLARE @MyTable TABLE (Product VARCHAR(10), Customer VARCHAR(10), TxDate SMALLDATETIME, Qty TINYINT)
INSERT INTO @MyTable(Product, Customer, TxDate, Qty )
VALUES
('Apple', 'Peter', '2013/02/02', 3),
('Apple', 'Edward', '2013/02/03', 5),
('Apple', 'Sally', '2013/02/06', 3),
('Apple', 'Emily', '2013/02/08', 6),
('Orange', 'Ray', '2013/02/03', 5),
('Orange', 'Simon', '2013/02/04', 4),
('Orange', 'Billy', '2013/02/05', 5),
('Orange', 'David', '2013/02/06', 2);
-- calculation
DECLARE @MyTable1 TABLE (Id TINYINT, Product VARCHAR(10), Customer VARCHAR(10), TxDate SMALLDATETIME, Qty TINYINT, CumSum INT);
WITH itemized
AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY Product ORDER BY TxDate) AS PurchaseNo
FROM @MyTable
)
INSERT INTO @MyTable1
SELECT PurchaseNo, Product, Customer, TxDate, Qty,
CumSum =
(
SELECT
SUM (i2.Qty)
FROM itemized i2
WHERE i2.Product = i1.Product AND i2.PurchaseNo <= i1.PurchaseNo
)
FROM itemized i1
WHERE i1.PurchaseNo <=10;
SELECT
intermideate.Product,
intermideate.Customer,
intermideate.TxDate,
CASE
WHEN intermideate.Id = final.MinIdAbove10 THEN intermideate.Qty - final.Correction
ELSE intermideate.Qty
END
FROM
(
SELECT t1.Product,
MinIdAbove10 =
(
SELECT MIN(t2.Id)
FROM @MyTable1 t2
WHERE t2.CumSum >= 10 and t2.Product = t1.product
),
Correction =
(
SELECT MIN(t2.CumSum - 10)
FROM @MyTable1 t2
WHERE t2.CumSum >= 10 and t2.Product = t1.product
)
FROM @MyTable1 t1
GROUP BY t1.Product
) final
INNER JOIN @MyTable1 intermideate
ON intermideate.Product = final.Product AND intermideate.Id <= final.MinIdAbove10