从其他两个表中选择SUM

时间:2013-08-01 04:57:29

标签: sql select sum

我有此查询并成功获取totstock

SELECT p.pid,p.product_name,SUM(s.qty) as totstock
FROM tblproducts p
LEFT JOIN tblstocks s ON s.pid=p.pid
GROUP BY p.pid

但是当我尝试加入我的第二个表时,总错误totstocktotsales 我有这个查询,但我认为这是错误的

SELECT p.pid,p.product_name,SUM(s.qty) as totstock,SUM(sl.qty) as totsale
FROM tblproducts p
LEFT JOIN tblstocks s ON s.pid=p.pid
LEFT JOIN tbls sl ON sl.pid=p.pid
GROUP BY p.pid

产品 - tblproducts

pid  |   product_name
 1   |  pencil
 2   |  paper 

股票 - tblstocks

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

销售 - tbls

 pid  |  qty
  1   |   2
  1   |   1

我想要的结果是

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

2 个答案:

答案 0 :(得分:3)

SELECT p.pid,p.product_name,totstock, totsale
FROM tblproducts p
LEFT JOIN (Select pid, Sum(qty) as totstock from tblstocks group by pid)  s ON s.pid=p.pid
LEFT JOIN (Select pid, Sum(qty) as totsale from tbls group by pid) sl ON sl.pid=p.pid

Sql Fiddle Demo

答案 1 :(得分:0)

  

也可以在p.product_name上尝试使用组。我认为这将解决问题   问题。