求一条sql语句,部门人数统计问题

tw2000 2003-07-05 10:29:24
两张表
部门(部门ID,部门名称,上级部门ID,...)
人员 (人员ID ,所属部门ID,...)
假设有三层部门,如何设计一个SQL语句,
使得能够查询到全部第二层部门的人员统计清单,(包含本级直属的以及下级部门所属的人员),如何做?
我初步的打算是
select 部门ID ,count(人员ID ) from 人员 right outer join 部门 on
部门.部门ID = 人员.所属部门ID group by 部门ID
以上查询了直属的人员数量,但是下属的人员数量如何查询呢?
高手帮帮忙!
...全文
535 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
tw2000 2003-07-06
  • 打赏
  • 举报
回复
好厉害,i 服了
happydreamer 2003-07-05
  • 打赏
  • 举报
回复
declare @temp table (id char(8))

insert @temp values ('上级部门的ID值')

while exists (
select id from 部门
where 上级部门ID in (select id from @temp)
and 部门ID not in (select id from @temp)
)
insert @temp
select id from 部门
where 上级部门ID in (select id from @temp)
and 部门ID not in (select id from @temp)
---把所有子部门ID插入@temp


select a.部门ID,count(b.人员ID )
from 部门 a join 人员 b on a.部门ID=b.所属部门ID
where a.部门ID in (select id from @temp)
group by a.部门ID

34,593

社区成员

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

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