recursive sql function with rollup logic?

后端 未结 3 858
感情败类
感情败类 2021-01-28 23:33

i have a SQL that using a recursive CTE to expand a self-referancing employees table builds a result set of defects aggregated by user and severity level.

here is my CTE

3条回答
  •  误落风尘
    2021-01-29 00:22

    If you modified your cte to include the depth i.e.

    WITH yourcte AS  
      (  
        SELECT EmployeeId, ManagerNTID, ManagerID, NTID, FullName, 0 AS Depth
        FROM Employees  
        WHERE NTID = @NTID
        UNION ALL  
        SELECT e.EmployeeId, e.ManagerNTID, e.ManagerID, e.NTID, e.FullName, y.Depth + 1
        FROM Employees e  
        JOIN yourcte y ON e.ManagerNTID = y.NTID
      )
    

    You can then order your output by depth (as the user in the input parameter should be at depth zero). Using this you should also be able to limit the depths you return and aggregate defects where depth >= 1


    Edit

    With the SQL I added above you basically want to rollup all defects to the user at Level 1? So, the NTID of the user at this level becomes the group by item for all records with depth >= 1. Another edit to the cte below adds the NTID as GroupingID which you can use to group by / rollup

    WITH yourcte AS  
      (  
        SELECT EmployeeId, ManagerNTID, ManagerID, NTID
              ,FullName, 0 AS Depth, NTID as GroupingID
        FROM Employees  
        WHERE NTID = @NTID
        UNION ALL  
        SELECT e.EmployeeId, e.ManagerNTID, e.ManagerID, e.NTID
              ,e.FullName, y.Depth + 1, CASE
                                           WHEN y.Depth + 1 = 1 THEN e.NTID
                                           ELSE y.GroupingId
                                        END
        FROM Employees e  
        JOIN yourcte y ON e.ManagerNTID = y.NTID
      )
    

提交回复
热议问题