首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

|ZYCSQL| 求SQL,根据下上级来统计公车数量

2012-12-27 
|ZYCSQL| 求SQL,根据上下级来统计公车数量如有地区表ID名称上级ID1广州null2天河13越秀14白云15太和46人和

|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

*/

热点排行