sql - Select SUM from two other tables -


i have query , gets totstock

select p.pid,p.product_name,sum(s.qty) totstock tblproducts p left join tblstocks s on s.pid=p.pid group p.pid 

but when tried join second table gets wrong total totstock , totsales have query think wrong

select p.pid,p.product_name,sum(s.qty) totstock,sum(sl.qty) totsale tblproducts p left join tblstocks s on s.pid=p.pid left join tbls sl on sl.pid=p.pid group p.pid 

products - tblproducts

pid  |   product_name  1   |  pencil  2   |  paper  

stocks - tblstocks

 pid  |  qty   1    |   1  1    |   3  1    |   5 

sales - tbls

 pid  |  qty   1   |   2   1   |   1 

the result want is

pid  | name    | totstock | totsales  1   |  pencil |    9     |    3    2   |  paper  |  null    |  null 

select p.pid,p.product_name,totstock, totsale tblproducts p left join (select pid, sum(qty) totstock tblstocks group pid)  s on s.pid=p.pid left join (select pid, sum(qty) totsale tbls group pid) sl on sl.pid=p.pid 

sql fiddle demo


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -