请问逐级向下统计的这样SQL语句该怎么写?

zjkun15 2003-08-26 10:24:59
数据库table1中有如下字段
ID TOPID
1 2
2 0
3 2
4 3
5 3
.........
table2中有如下字段
id countperson departmentname
1 22 ****
2 11 **
3 55 ***
4 545 **
5 44 **
......
要求用一条sql语句得出不同departmentname下的总人数(包括本层的人数和所有下级)
...全文
107 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengdali 2003-08-26
  • 打赏
  • 举报
回复
create table #table1(ID int,TOPID int)
insert #table1 values(1, 2)
insert #table1 values(2 , 0)
insert #table1 values(3 , 2)
insert #table1 values(4 , 3)
insert #table1 values(5 , 3)
create table #table2(id int,countperson int,departmentname varchar(100))
insert #table2 values(1, 22 , '****')
insert #table2 values(2 , 11 , '**')
insert #table2 values(3 , 55 , '***')
insert #table2 values(4 , 545, '**')
insert #table2 values(5 , 44, '**')

select *,null 人数 into #result from #table2

declare @tmp1 table (Id int,pid int)

while exists(select 1 from #result where 人数 is null)
begin

insert @tmp1 select * from #table1 where ID=(select min(id) from #result where 人数 is null)

while exists(select 1 from #table1 where topID in (select id from @tmp1) and id not in (select id from @tmp1))
insert @tmp1 select * from #table1 where TOPID in (select id from @tmp1) and id not in (select id from @tmp1)

update #result set 人数=(select sum(countperson) from #table2 where id in (select id from @tmp1)) where id=(select min(id) from #result where 人数 is null)
delete @tmp1
end
select * from #result
go
drop table #table1,#table2,#result

--注意 #table1,#table2 分别为你的表,#result是结果临时表

(SQLServer MVP 大力)
zjkun15 2003-08-26
  • 打赏
  • 举报
回复
对是用ID关联的!
txlicenhe 2003-08-26
  • 打赏
  • 举报
回复
上下级关系怎样定义?两表如何关联,id?
ZHANGWEI15 2003-08-26
  • 打赏
  • 举报
回复
--try it

select
t2.id,
t2.departmentname,
(select sum(tt2.countperson) from table2 tt2
where tt2.id=t2.id or tt2.id in (select t1.id from table1 t1 where t1.topid=t2.id )
) as total
from table2 t2
lllqe 2003-08-26
  • 打赏
  • 举报
回复
up
CrazyFor 2003-08-26
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/1375/1375432.xml?temp=.8570978

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧