I got nearly the same thing but it will work with multiple SKUs. Did we get it wrong or is your expected output out of sync with your sample data?declare @PROD table (DATE datetime, SKU int, QTY int)insert @prodselect '8/24/09', 1012, 7 union allselect '8/25/09', 1012, 12 union allselect '8/26/09', 1012, 6declare @SALES table (DATE datetime, SKU int, QTY int)insert @salesselect '8/24/09', 1012, -15 union allselect '8/25/09', 1012, -11 union allselect '8/26/09', 1012, -9declare @INVEN table (DATE datetime, SKU int, QTY int)insert @invenselect '8/24/09', 1012, 50;with cte as( select ca.Date ,i.sku ,ca.qty from ( select sku from @inven i group by sku ) i cross apply ( select top 1 Date, Qty from @inven where sku = i.sku order by date desc ) ca union all select p.date ,i.sku ,i.qty + isNull(p.qty, 0) + isNull(s.qty,0) from cte i inner join @prod p on p.sku = i.sku and p.date = dateadd(day, 1, i.date) inner join @sales s on s.sku = i.sku and s.date = p.date)select date, sku, qty from cteoutput:date sku qty----------------------- ----------- -----------2009-08-24 00:00:00.000 1012 502009-08-25 00:00:00.000 1012 512009-08-26 00:00:00.000 1012 48
Be One with the OptimizerTG