I'm trying to combine some sales and purchase information into a single table grouped by item code. On both the sales and purchase side there is a Header table and a Detail table, all the info I want is in Detail but I need to join to the Header so I can filter by date. I want to combine the sales and purchase data into a single line according to item code, so I've been using a UNION query. A simplified version of the query looks like this:
P/S = Purchase/Sale
D/H = Detail/Header
Code:
SELECT P_D.ITEM as [ITEM], SUM(P_D.ORDQTY) as [P_QTY], SUM(0) AS [S_QTY]
FROM P_H INNER JOIN P_D ON P_H.P_NUMBER = P_D.P_NUMBER
WHERE P_H.P_DATE Between [Start Date] And [End Date]
GROUP BY P_D.CODE
UNION
SELECT S_D.ITEM as [ITEM], SUM(0) as [P_QTY], SUM(S_D.ORDQTY) as [S_QTY]
FROM S_H INNER JOIN S_D ON S_H.P_NUMBER = S_D.P_NUMBER
WHERE S_H.S_DATE Between [Start Date] And [End Date]
GROUP BY S_D.CODE;
The result I want would look like this:
ITEM |
P_QTY |
S_QTY |
Item1 |
10 |
5 |
Item2 |
20 |
12 |
But the results I'm getting is:
ITEM |
P_QTY |
S_QTY |
Item1 |
10 |
0 |
Item1 |
0 |
5 |
Item2 |
20 |
0 |
Item2 |
0 |
12 |
I can understand why I'm getting those results and I'm sure I've done this before but I can't quite recall how to get the results I want.
Any help would be appreciated, thanks.