如何在Sql中从一个表到另一个表获取项目总和

时间:2019-02-07 17:28:08

标签: sql sql-server

如何在sql中从一个表到另一个表获取项的总和

enter image description here

3 个答案:

答案 0 :(得分:1)

使用联接和子查询

   select p.*,stock from theProduct p
    join ( select prodcode,sum(Qty) as stock from thePurchaseDetail group by prodcode) t
      on p.prodcode=t.prodcode

答案 1 :(得分:1)

您可以使用APPLY

select p.*, pp.stock 
from theProduct p cross apply
     (select sum(pp.qty) as stock 
      from thePurchaseDetail pp
      where pp.prodcode = p.prodcode
     ) pp;

您还可以将窗口功能与JOIN一起使用:

select p.*, sum(pp.qty) over (partition by p.prodcode) as stock
from theProduct p inner join
     thePurchaseDetail pp
     on pp.prodcode = p.prodcode;

答案 2 :(得分:0)

如果tblPurchaseDetail表中缺少产品代码,您将退出联接

    select p.*
          ,t.stock 
     from tblProduct p
left join ( select prodcode
                  ,sum(Qty) as stock 
             from tblPurchaseDetail 
            group by prodcode
           ) t
      on p.prodcode=t.prodcode