A simple version using sub-select for getting quantity on hand per day.
A good / quick solution if you dont have 100k's transactions and/or a decent sql box.
Excuse the messy SQL (lunchtime coding :P )
CREATE TABLE #transactions (ID INT, DTE DATETIME, PROD VARCHAR(25), QTY INT ) CREATE TABLE #products (ID VARCHAR(25)) CREATE TABLE #dates (DTE DATETIME) -- create some dates - you would do this dynamically INSERT INTO #dates values (convert(datetime, '01/01/2011', 103)) INSERT INTO #dates values (convert(datetime, '02/01/2011', 103)) INSERT INTO #dates values (convert(datetime, '03/01/2011', 103)) -- create some products - you would get these from where-ever they live INSERT INTO #products values ('A') INSERT INTO #products values ('B') -- create some transactions - you would get these from where-ever they live INSERT INTO #transactions values (1, convert(datetime, '01/01/2011', 103), 'A', 25) INSERT INTO #transactions values (2, convert(datetime, '01/01/2011', 103), 'A', -5) INSERT INTO #transactions values (3, convert(datetime, '02/01/2011', 103), 'A', 60) INSERT INTO #transactions values (4, convert(datetime, '02/01/2011', 103), 'A', -15) INSERT INTO #transactions values (5, convert(datetime, '03/01/2011', 103), 'A', 100) INSERT INTO #transactions values (6, convert(datetime, '03/01/2011', 103), 'A', -20) INSERT INTO #transactions values (7, convert(datetime, '01/01/2011', 103), 'B', 10) INSERT INTO #transactions values (8, convert(datetime, '01/01/2011', 103), 'B', 5) INSERT INTO #transactions values (9, convert(datetime, '02/01/2011', 103), 'B', -30) INSERT INTO #transactions values (1, convert(datetime, '02/01/2011', 103), 'B', 50) INSERT INTO #transactions values (11, convert(datetime, '03/01/2011', 103), 'B', 10) INSERT INTO #transactions values (12, convert(datetime, '03/01/2011', 103), 'B', 200) -- Join dates and transactions - Do a sub select from 'begining of time' to get qty on hand per day SELECT CONVERT(VARCHAR(25), a.DTE, 103), b.id, (SELECT sum(qty) from #transactions c where b.id = c.prod and c.DTE <= a.DTE) FROM #dates a, #products b -- One benefit to this approach means you can genereate qty_on_hand per days were no transactions have occured (if you needed this) DROP TABLE #transactions DROP TABLE #products DROP TABLE #dates
12/31/2010in the input?Itemstable has the "running balance" at current time. He then wants the "history" from an arbitrary day (start day) in the past, from say01/01/2011up to now (or another arbitrary day).12/31/2010is the previous day of the "start day".