日期:2014-05-17  浏览次数:20478 次

|ZYCSQL| 求SQL,根据上下级来统计公车数量
如有地区表
ID    名称   上级ID
1     广州   null
2     天河   1
3     越秀   1
4     白云   1
5     太和   4
6     人和   4
--------------------
如以上是一个广州的地区表
然后有公车表
公车表(这里的数量是他们各自的单位有的车数)
AreaID  BusCount
1       100
2       120
3       150
4       120
5       50
6       20
-----------------------
然后我要出结果
地区公车总数
Area  AllBusCount
1     560    //这里为 广州 + 他子地址(天河,越秀,白云(白云下面的))
2     120
3     150
4     190    //这里白云的就是白云+他子地址(太和+人和)
5     50
6     20
---------------------------------------
如何写出以上查询 
谢谢
------最佳解决方案--------------------

--就是展bom哦
declare @t1 table(id int,name nvarchar(10),fid int)
insert into @t1 values(1,N'廣州',null)
insert into @t1 values(2,N'天河',1)
insert into @t1 values(3,N'越秀',1)
insert into @t1 values(4,N'白雲',1)
insert into @t1 values(5,N'太和',4)
insert into @t1 values(6,N'人和',4)

declare @t2 table (areaid int,buscount int)
insert into @t2 values(1,100)
insert into @t2 values(2,120)
insert into @t2 values(3,150)
insert into @t2 values(4,120)
insert into @t2 values(5,50)
insert into @t2 values(6,20)

;with cte
as
(
select id as topid,id,name
 from @t1 x1 
union all
select topid,B.id,A.name
from cte A ,@t1 B
where A.id=B.fid
)

select A.topid,A.name,sum(isnull(B.buscount,0)) as buscount
 from cte A
left join @t2 B
on A.id=B.areaid
group by A.topid,A.name
order by 1

/*
1 廣州 560
2 天河 120
3 越秀 150
4 白雲 190
5 太和 50
6 人和 20

*/