日期:2014-05-17 浏览次数:20445 次
--drop table t1
--drop table t2
create table t1(
部门ID int,
部门代码 varchar(20),
上级代码 varchar(10),
部门名称 varchar(20)
)
insert into t1
select 2, '0101', '01', '管理部'
union all select 3, '0102', '01', '市场支持部'
union all select 4, '0103', '01', '技术部'
union all select 7, '010101', '0101', '总务课'
union all select 8, '010102', '0101', '财务课'
union all select 9, '010201', '0102', '市场企划组'
create table t2
(
人员ID int, 部门ID int, 人员编号 varchar(20)
)
insert into t2
select 2, 2, '79503001'
union all select 3, 4, '79408005'
union all select 4, 7, '70911001'
union all select 5, 8, '71002004'
union all select 6, 9, '71002003'
union all select 7, 8, '71002002'
;with t
as
(
select t1.部门ID,
t1.部门代码,
t1.上级代码,
t1.部门名称,
count(*) as people_count
from t1
left join t2
on t1.部门ID = t2.部门ID
group by t1.部门ID,
t1.部门代码,
t1.上级代码,
t1.部门名称
)
select 部门ID,
部门代码,
(select sum(people_count)
from t t2
&nb