员工与下属和计数

时间:2017-12-06 15:24:23

标签: sql sql-server performance select

我使用以下查询来选择所有员工信息及其下属。我也需要计算下属总数。但是,我面临一个问题,当数据大小增长,超过12k行数据时,select语句变得极其缓慢。任何人都知道如何去做这个? 注意:empLogin和mgrLogin都是varchar(30)

DECLARE @v_empLogin varchar(30) = 'Albert21';
WITH EmployeeList
 AS (SELECT  empLogin, empName ,mgrLogin
 ,departmentID,0 AS Level
	 FROM   Employees 
	 WHERE  mgrLogin  =@v_empLogin 
	 and isActive =1
	 UNION ALL
	 SELECT usr.empLogin,usr.empName,usr. mgrLogin
	 ,usr.departmentID, mgr.[Level] + 1
	 FROM   Employees  AS usr
     INNER JOIN EmployeeList AS mgr ON usr. mgrLogin = mgr.empLogin 
	 WHERE  usr.mgrLogin  IS NOT NULL
	 AND usr.isActive=1 and usr.empLogin  
	 )


SELECT u.empLogin , u.empName, u.mgrLogin
,u.departmentID, u.EmpLevel , mg.Total,u.isActive  
FROM   EmployeeList AS u
left JOIN (SELECT u.mgrLogin , COUNT(empLogin) as 'Total'
FROM   EmployeeList AS u group by u.mgrLogin )
mg on mg.mgrLogin  = u.empLogin 

0 个答案:

没有答案