i have a problem, i have a table were i keep the incoming and other one were i keep the outgoing records, the thing that i need to do is to group these records by partNumber and have a single output.
InTable
PartNo Qty Date
A 1 1/1/13
A 5 1/1/13
B 2 1/1/13
OutTable
PartNo Qty Date
A 2 1/1/13
B 1 1/1/13
C 3 1/1/13
Result Needed
Date 1/1/13
PartNo In Out Total
A 6 2 4
B 2 1 1
C 0 3 -3
I have tried something like this but it results on the totals because of the sum(qty), but it does not work any other way.
select a.PartNo, sum(b.inQty) as inQty,sum(c.outQty) as outQty, sum(b.inQty)-sum(c.outQty) as total from
(Select PartNo FROM InTable
where date= '01-01-2013'
group by PartNo
union
Select PartNo FROM OutTable
where date= '01-01-2013'
group by PartNo) A
cross join
(
SELECT PartNo,SUM(Qty) inQty FROM InTable
where date= '01-01-2013'
group by PartNo
)B
cross join
(
SELECT PartNo,SUM(Qty) outQty FROM OutTable
where date= '01-01-2013'
group by PartNo
)c
group by a.PartNo
There i tried to join three queries, each query individually results in something helpfull, but the problem is when i try to join them, the query will result in something like
PartNo inQty outQty total
A 8 6 2
B 8 6 2
C 8 6 2
Any sugestions?, thanks.
Use a Full Outer Join on two Derived Tables:
SELECT
COALESCE(inTab.PartNo, outTab.PartNo) AS PartNo,
COALESCE(inQty, 0),
COALESCE(outQty, 0),
COALESCE(inQty, 0) - COALESCE(outQty, 0) AS total
FROM
(
SELECT PartNo, SUM(Qty) AS inQty
FROM InTable
WHERE DATE= '01-01-2013'
GROUP BY PartNo
) InTab
FULL JOIN
(
SELECT PartNo, SUM(Qty) AS outQty
FROM OutTable
WHERE DATE= '01-01-2013'
GROUP BY PartNo
) OutTab
ON inTab.Partno = outTab.PartNo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With