, - OUTER APPLY :
DECLARE @InventoryTransactions TABLE ([Date] DATE, Sold INT, Purchased INT)
INSERT @InventoryTransactions VALUES
('20120504', 1, 0),
('20120503', 6, 0),
('20120501', 0, 5),
('20120425', 103, 0),
('20120415', 0, 100)
SELECT trans.Date,
trans.Sold,
trans.Purchased,
ISNULL(Balance, 0) [BalanceIn],
ISNULL(Balance, 0) + (Purchased - Sold) [BalanceOut]
FROM @InventoryTransactions trans
OUTER APPLY
( SELECT SUM(Purchased - Sold) [Balance]
FROM @InventoryTransactions bal
WHERE Bal.Date < trans.Date
) bal
. , LEFT JOIN , . , (- dbo.Calendar), , , , CTE, . , ,
, , , ( ).
;WITH Transactions AS
( SELECT trans.Date,
trans.Sold,
trans.Purchased,
ISNULL(Balance, 0) [BalanceIn],
ISNULL(Balance, 0) + (Purchased - Sold) [BalanceOut]
FROM @InventoryTransactions trans
OUTER APPLY
( SELECT SUM(Purchased - Sold) [Balance]
FROM @InventoryTransactions bal
WHERE Bal.Date < trans.Date
) bal
)
SELECT DATEDIFF(DAY, MAX(Date), CURRENT_TIMESTAMP) [Days Since Negative Balance]
FROM Transactions
WHERE BalanceIn > 0
2
SQL Fiddle, OUTER APPLY . , CTE , , 17% , 83% CTE.