日期:2014-05-18 浏览次数:20771 次
表A: ID Qty 10 0 101 100 102 200 20 0 201 500 表B: ID ParentID 101 10 102 10 201 20 现在需要得出如下结果: ID Qty 10 300 101 100 102 200 20 500 201 500
-- 建表
create table ta(id int, qty int);
insert into ta
select 10,0 union all
select 101,100 union all
select 102,200 union all
select 20,0 union all
select 201,500;
create table tb(ID int, ParentID int);
insert into tb
select 101,10 union all
select 102,10 union all
select 201,20;
-- 查询
select id,
qty=case when (select COUNT(*) from tb where tb.ParentID=ta.id)>0
then isnull((
select sum(c.qty) from ta c where c.id in(select id from tb where parentid=ta.id)
),0)
else qty end
from ta
-- 结果
10 300
101 100
102 200
20 500
201 500
------解决方案--------------------
select a.id,Sum(Case when b.ParentID Is Null then a.qty else c.qty End) from ta a
left outer join tb b on a.id=b.ParentID
left outer join ta c on b.id=c.id
Group by a.id