日期:2014-05-17  浏览次数:20397 次

统计各部门人数
部门  编号
A1    001
A1    002 
A101  003
A101  004
A101  005
B1    006
B1    007
B1    008
B101  009
C1    010
C1    011
C1    012
C1    013

实现效果
A1    5
A101  3
B1    4
B101  1
C1    4


------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

Quote: 引用:

部门ID  部门代码 上级代码 部门名称
2 0101 01 管理部
3 0102 01 市场支持部
4 0103 01 技术部
7 010101 0101 总务课
8 010102 0101 财务课
9 010201 0102 市场企划组

人员ID  部门ID  人员编号
2 55 79503001
3 55 79408005
4 27 70911001
5 28 71002001 


你的部门ID和上面的部门ID,都不对应啊。
 额,这个是部分数据


呵呵,没事,就是人员的那部分数据的部门ID,和上面的部门ID对不上哈。

能不能贴一点,能关联上的数据呢
 
也可以说统计子部门人数也要统计父级部门人数


呵呵,你太实诚了,贴了那么多的数据,我就模拟了几条数据哈,是这个效果吗:


--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