I need to write a SELECT
query in SQL Server which uses a JOIN
or UNION
that selects distinct ItmNo
or Code
rows from 3 tables OnHand
, Sale
and Purchase
.
Here are the details of the tables I have and what I need. ItmNo
and/or Code
columns can be used as foreign keys to join the tables.
These are my input tables-
Table OnHand
ID ItmNo Code Qty
----------------------------------
1 I001 001 100
2 I001 001 50
3 I003 003 300
Table Sale
ID ItmNo Code Qty
----------------------------------
1 I001 001 100
2 I004 004
3 I003 003 120
Table Purchase
ID ItmNo Code Qty
----------------------------------
1 I005 005 10
2 I003 003 200
3 I003 003 300
And this is what I need as output. Only DISTINCT ItmNo
and Code
should be displayed here:
ID ItmNo Code SumQtyOnHand SumQtyOnSale SumQtyOnPurchase
------------------------------------------------------------------------------
1 I001 001 150 100
2 I003 003 300 120 500
3 I005 005 10
Here is the SELECT
query that I have tried is below but I cannot get the output I want-
SELECT
A.ItmNo, A.Code,
A2.TOTAL SumQtyOnHand,
B.TOTAL SumQtyOnSale,
C.TOTAL SumQtyOnPurchase
FROM
dbo.OnHand A
LEFT JOIN
(SELECT ItmNo, Code, SUM(Qty) TOTAL
FROM dbo.OnHand
GROUP BY ItmNo, Code) A2 ON A.ItmNo = A2.ItmNo
LEFT JOIN
(SELECT ItmNo, Code, SUM(Qty) TOTAL
FROM dbo.Sale
GROUP BY ItmNo, Code) B ON A.ItmNo = A2.ItmNo
LEFT JOIN
(SELECT ItmNo, Code, SUM(Qty) TOTAL
FROM dbo.Purchase
GROUP BY ItmNo, Code) C ON A.ItmNo = A2.ItmNo
Please suggest the correction in the SELECT
query to achieve the above output.
Thanks in advance!