SQL aggregated by person to department tree recursive total total function

Source: Internet
Author: User

1, the total number of people calculated, in the department tree (trees) by structure (master parent binding)

CREATE function [dbo]. [Getempdepnum] (@IDint) RETURNS @Tree Table (ID [int] IDENTITY (1,1), PID Int,fid int,sn Varchar ( Max), Name Varchar ( Max), Num Varchar ( Max)) asBEGIN DECLARE @MaxNumint, @iint, @fint, @sNnmintInsert @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@TreeBcbSELECT @MaxNum=count (*) from@TreeSet@i=1   while(@i<=@MaxNum) BeginSelect@f=fid from@TreewhereId=@iSelect@sNnm =sum (CONVERT (int, num)) from@TreewhereFid= (SelectFid from@TreewhereId=@i)--print'S | |'+convert (varchar ( -), @i) +'|'+convert (varchar ( -), @sNnm)if@sNnm >0Begin update @TreeSetNum [email protected] from@TreewherePid=@f End SET @i[Email protected]+1End--Select* from@TreeBcb ORDER by FID Desc,pid--SelectPID, Fid,case Num when0Then Name ELSE name+' ('+num+')'END asName from@TreeBcb ORDER by FID Desc,pid returnend GO

2. Call

Select 0 then Name ELSE name+'  ('+num+')'as Name from   dbo. Getempdepnum (0)  

SQL is aggregated by people into the departmental tree recursive total totals function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.