日期:2014-05-18  浏览次数:20486 次

求sql递归求人员的一级部门信息
表结构:
部门表:
id(部门id)         name(部门名称)             parentid(部门上级部门ID,0为一级部门)
1                                     技术部                                     0
2                                     销售部                                     0
3                                     上海技术部                             1
4                                     上海技术部-网络组               3
......

人员表:
id                             username                             did(最小等级部门ID)
1                                   张三                                   1
2                                   李四                                   4
3                                   王五                                   2
4                                   马六                                   3
......


问题1、现在要根据人的ID(比如李四或马六的ID)求他所在一级部门,部门分级不局限于三级,可能更多,用递归怎么做sql语句?
例,李四ID=2
获得结果:2       李四     技术部       1(技术部ID)
马六ID=4
获得结果:4       马六     技术部       1


问题2、求一级部门列表,并且列出部门所有人数,sql怎么写?

输出结果:
1       技术部         3(人数)
2       销售部         1


求高手指教,问题解决马上结贴!

------解决方案--------------------
create table department(id int,name varchar(20),parentid int)
insert into department select 1, '技术部 ',0
insert into department select 2, '销售部 ',0
insert into department select 3, '上海技术部 ',1
insert into department select 4, '上海技术部-网络组 ',3

create table employee(id int,username varchar(8),did int)
insert into employee select 1, '张三 ',1
insert into employee select 2, '李四 ',4
insert into employee select 3, '王五 ',2
insert into employee select 4, '马六 ',3
go

create function f_getRootId(@did int)