I have these SQL tables
Supplier
SUPPLIERID | SUPPLIERNAME
1 | sup1
2 | sup2
3 | sup3
Sold
ITEMID | SOLD | SUPPLIER ID | DATE
pen | 10 | 1 | 2011-10-21
pen | 5 | 1 | 2011-10-22
pen | 5 | 1 | 2011-10-23
pen | 20 | 3 | 2011-10-24
Bought
ITEMID | BOUGHT | SUPPLIER ID | DATE
pen | 20 | 1 | 2011-9-21
pen | 5 | 3 | 2011-9-24
I’m currently using this script but it doesn’t seem to work as the SUM() of sold and bought is tripled. I suspect the reason is because there are 3 rows in sold but only 2 in bought. Any idea how to fix this?
SELECT suppliername, SUM(sold) as sold, SUM(bought) AS bought
FROM sold s
LEFT JOIN supplier sp
ON s.supplierid = sp.supplierid
LEFT JOIN bought b
ON sp.supplierid = b.supplierid
GROUP BY suppliername
Basically, what I’m doing is calculating the amount sold and the amount bought for every supplierId separately (in the
LEFT JOINs), so I always have the total amount sold and total amount bought. The querys that I’m using in theLEFT JOINs are called derived tables, since they are acting like a table on the general query. Hope this helps you get a more clear idea of what I did.