求教sql连表查询
表A:
k_dkdajlh dkje
----------- -------
699714DC 123.00
表B:
k_dkdajlh hkje
--------- ---------------------
699714DC 3000.00
699714DC 2000.00
我想查询返回 dkje 和 sum(hkje) 两个字段 只返回一行
我用left join 总是返回两行
select A.dkje, sum(B.hkje)
from A left join B
on A.k_dkdajlh=B.k_dkdajlh
where A.k_dkdajlh='699714DC'
group by A.dkje,B.hkje
------解决方案--------------------
declare @k_dkdajlh nvarchar(100)
set @k_dkdajlh='699714DC'
with cte as(
select k_dkdajlh,sum(hkje) as hkje
from B
group by k_dkdajlh
)
select A.dkje,B.hkje from A join cte B on A.k_dkdajlh=B.k_dkdajlh
where A.k_dkdajlh= @k_dkdajlh