Pearlfromsu

less3

Dec 2nd, 2024
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.02 KB | None | 0 0
  1. WITH DeptHierarchy AS (
  2.     SELECT
  3.         ID as UnitID,
  4.         DepartmentName as UnitName,
  5.         ParentID as UpperUnitID,
  6.         CAST('' AS NVARCHAR(MAX)) AS NavigationalPath,
  7.         0 AS DepthLevel
  8.     FROM tblDepartment
  9.     WHERE ParentID IS NULL
  10.  
  11.     UNION ALL
  12.  
  13.     SELECT
  14.         d.ID as UnitID,
  15.         d.DepartmentName as UnitName,
  16.         d.ParentID as UpperUnitID,
  17.         CASE WHEN h.DepthLevel = 0 THEN d.DepartmentName ELSE h.NavigationalPath + '-' + d.DepartmentName END AS NavigationalPath,
  18.         h.DepthLevel + 1
  19.     FROM tblDepartment d
  20.     JOIN DeptHierarchy h ON d.ParentID = h.UnitID
  21. )
  22. SELECT
  23.     DepthLevel as Cnt,
  24.     UnitName AS Department,
  25.     NavigationalPath AS Path
  26. FROM (
  27.     SELECT
  28.         TOP 1 WITH TIES
  29.         DepthLevel,
  30.         UnitName,
  31.         NavigationalPath,
  32.         UpperUnitID,
  33.         UnitID
  34.     FROM DeptHierarchy
  35.     GROUP BY DepthLevel, UnitName, NavigationalPath, UpperUnitID, UnitID
  36.     ORDER BY DepthLevel DESC
  37. ) r1
  38. ORDER BY UpperUnitID DESC, UnitID
  39.  
Add Comment
Please, Sign In to add comment