答案 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