I think this will work (please note how I supplied some test data):
DECLARE @inventory_history table(itm_code INT, tran_type VARCHAR(15), itm_qty INT, doc_date datetime)
DECLARE @date DATETIME
SET @date = '3/31/2009'
INSERT INTO @inventory_history (
itm_code,
tran_type,
itm_qty,
doc_date
)
SELECT
1,
'Received',
100,
'3/28/09'
UNION ALL
SELECT
1,
'Allocated',
25,
'3/30/09'
UNION ALL
SELECT
1,
'Received',
50,
'4/2/09'
UNION ALL
SELECT
1,
'Allocated',
80,
'4/05/09'
SELECT
itm_code,
SUM(CASE WHEN tran_type = 'Received' THEN itm_qty ELSE itm_qty * -1 END) AS quantity
FROM
@inventory_history
WHERE
doc_date <= @date
GROUP BY
itm_code
This assumes that all transactions are stored in positive numbers so I need to reverse the sign on all other transactions other than receipts. You should be able to figure out the rest.
Jack Corbett
Consultant - Straight Path Solutions
Check out these links on how to get faster and more accurate answers:
Forum Etiquette: How to post data/code on a forum to get the best help
Need an Answer? Actually, No ... You Need a Question