I've got two tables, INPUT and OUTPUT.
INPUT table with columns ID, productName, QTY, buyPrice, sellPrice. OUTPUT table with columns ID, productName, QTY. Both can have multiple inputs with same productName and different (or same) QTY. OUTPUT can't have productName that doesn't appear in INPUT table first.
I'm trying to query both tables and to get the end result - something like this: productName, SUM(QTY) from INPUT table (GROUP BY productName), productName, SUM(QTY) from OUTPUT (GROUP BY productName)
Example:
INPUT
ID | productName | QTY | buyPrice | sellPrice
1 | dress 007 | 2 | 700 | 1400
2 | shirt 001 | 4 | 800 | 1900
3 | dress 007 | 10 | 700 | 1500
4 | dress 007 | 6 | 900 | 2900
5 | shirt 001 | 2 | 750 | 1600
6 | hat 008 | 2 | 300 | 600
OUTPUT
ID | productName | QTY
1 | dress 007 | 4
2 | shirt 001 | 2
3 | dress 007 | 1
4 | dress 007 | 1
5 | shirt 001 | 3
RESULT SHOULD BE
productName | SUM(QTY)INPUT | productName | SUM(QTY)OUTPUT
dress 007 | 18 | dress 007 | 6
shirt 001 | 6 | shirt 001 | 5
hat 008 | 2 | null | null
It's easy to do the SUM and GROUP when it's only one table, but when I try to LEFT JOIN both tables and GROUP by productName I get wrong values for SUMs. Where am I mistaken?
Easy part:
SELECT a.productName , SUM(a.QTY), a.buyPrice , a.sellPrice
FROM input a
GROUP BY a.productName
Error:
SELECT a.productName , SUM(a.QTY), b.productName , SUM(b.QTY)
FROM input a LEFT JOIN output b
ON a.productName = b.productName
GROUP BY a.productName