I am required to find the name of the product (iname) where total delivery quantity is equal to the total sales quantity
Two tables given are
sale: snum:sqty:iname 1 :3 :Shoes 2 :1 :Shoes 3 :1 :Hat delivery: dnum:dqty:iname 1 :5 :Shoes 2 :1 :Hat 3 :3 :Shoes
I tried this code but the result I got is aggregated incorrectly because there are multiple sales and deliveries of the same item
select sale.iname from sale inner join delivery on sale.iname = delivery.iname group by sale.iname having sum(delivery.dqty) - sum(sale.sqty) = 0
When I do the following I was able to find the correct total quantity but is there a way I can do this in one code?
select iname, sum(sqty) from sale group by iname select iname, sum(dqty) from delivery group by iname
Advertisement
Answer
You can try below –
select a.iname,saleQty,deliveryQty from ( select iname, sum(sqty) as saleQty from sale group by iname )A inner join ( select iname, sum(dqty) as deliveryQty from delivery group by iname )B on A.iname=B.iname where saleQty-deliveryQty=0