码迷,mamicode.com
首页 > 数据库 > 详细

SQL 由人员汇总到部门树递归合计总数函数

时间:2016-09-06 19:39:20      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

1、由人员计算出总数,在部门树(tree)按结构汇总(主父绑定)

CREATE function [dbo].[GetEmpDepNum]
(
    @ID int
)
RETURNS @Tree Table (ID [int] IDENTITY (1, 1),PID  Int,FID Int,SN Varchar(150), Name Varchar(150), Num Varchar(150))
as
begin 
declare @MaxNum int,@i int,@f int,@sNnm int
Insert @Tree SELECT c1.pid,c1.fid,c1.sn,c1.Name,(SELECT COUNT(*) FROM dbo.tbEmployee c2 WHERE c2.MID = c1.pid) 
    AS sNum FROM tbDepList c1 order by FID desc,pid 
--   select * from @TreeBcb
SELECT  @MaxNum=Count(*) from @Tree
set @i=1
  while (@i<=@MaxNum)
    begin
        select @f=fid from @Tree where ID=@i
        select @sNnm=SUM(CONVERT(int,num)) from @Tree  where FID=(select fid from @Tree where ID=@i )
        --print s ||+CONVERT(varchar(100),@i)+|+CONVERT(varchar(100), @sNnm)
        if @sNnm>0
         begin
           update  @Tree set Num =@sNnm from @Tree where PID=@f
         end
    SET  @i=@i+1
  end
--select * from @TreeBcb  order by FID desc,pid 
--select PID, FID,CASE Num WHEN 0 THEN Name ELSE Name+ (+Num+) END as Name  from @TreeBcb  order by FID desc,pid 


Return
end 


GO

2、调用

select PID, FID,CASE Num WHEN 0 THEN Name ELSE Name+ (+Num+) END as Name  from dbo.GetEmpDepNum(0)  order by FID ,pid 

 

SQL 由人员汇总到部门树递归合计总数函数

标签:

原文地址:http://www.cnblogs.com/yimeishui/p/5846791.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!