1. 程式人生 > >部門人員統計(將下屬部門人數彙總於一級部門)

部門人員統計(將下屬部門人數彙總於一級部門)

表結構說明:

Dept表:

DeptID         DeptName                              ParentDeptID

1                   宜都市                                   0

2                   農業局                                   1

3                   紀委監察局                            1

4                  農業綜合執法大隊                  2 

5                  農業技術推廣中心                  2 

6                  特產技術推廣中心                  2

7                  黨風室                                    3 

8                  幹部室                                    3

Dept_User_Connection表:

CID         DeptID          UserID

1             2                    1

2             3                    2

3             4                    3

4             7                    4

5             8                    5

Users表:

UserID         UserName                             

1                  張三                                 

2                  李四                                   

3                  王五                    

4                  甲六                    

5                  丙丁           

需求說明:要求分組彙總 "宜都市" 所有下級部門人數總和。期望輸出結果如下:

DeptID         DeptName      DeptUserCount

2                   農業局            2

3                   紀委監察局     3

解題思路:

1.查詢 “農業局“ 及遞迴查詢其所有下屬部門;

with cte as
(
    select DeptID,ParentDeptID,DeptName,0 as lvl from Dept
    where DeptID=2
    union all
    select d.DeptID,d.ParentDeptID,d.DeptName,lvl+1 from cte c
    inner join Dept d on c.DeptID =d.ParentDeptID
)
select * from cte

go

2.建立標量函式,返回 ”農業局“ 關聯所有的人員總數;

CREATE FUNCTION GetDeptUserCount
(
 @DeptID int
)
RETURNS int
AS
BEGIN
DECLARE @targetData VARCHAR(100);
 with cte as
 (
  select DeptID,ParentDeptID,DeptName,0 as lvl from Dept
  where DeptID=@DeptID
  union all
  select d.DeptID,d.ParentDeptID,d.DeptName,lvl+1 from cte c
  inner join Dept d on c.DeptID =d.ParentDeptID
 )
 select @targetData=COALESCE(COUNT(Connection.IN_USER_ID),0) from cte
 INNER JOIN Dept_User_Connection Connection ON Connection.IN_DEPT_ID=cte.IN_DEPT_ID
 INNER JOIN Users ON Connection.IN_USER_ID = Users.IN_USER_ID
 RETURN @targetData ;
END

go

3.分組查詢 “宜都市“ 下級部門人員彙總資料。

 SELECT Dept.DeptID,Dept.DeptName,dbo.GetDeptUserCount(Dept.DeptID) FROM Dept
 WHERE ParentDeptID=1