/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu

Saturday, September 28, 2019

SQL important Hierarchy Queries

Common type expression for employee organisation hierarchy             

  ,OrgHierarchyLevel             
  As             
  (             
   SELECT Id, [Name], ParentID, LevelId FROM T_Organisation WHERE Id = @OrgId             
   UNION All             
   SELECT O.Id, O.[Name], O.ParentID, O.LevelId FROM T_Organisation O             
   INNER JOIN OrgHierarchyLevel OHL ON O.Id = OHL.ParentID             
  )           

Common type expression for employee organisation hierarchy sequence within one row using PIVOT Query:

DECLARE @OrgId INT = 100
;WITH OrgHierarchyLvl
As
(
SELECT
Id, Name, ParentID, LevelId
FROM
Organisation WHERE Id = @OrgId
UNION All
SELECT
ic.Id, ic.Name, ic.ParentID, ic.LevelId
FROM Organisation ic
INNER JOIN OrgHierarchyLvl cte ON ic.Id = cte.ParentID
)
,OrgSequence AS
(
SELECT @OrgId as OrgId,* FROM
(
SELECT LevelId,Name from OrgHierarchyLvl
) AS SourceTable
PIVOT(Max(Name) FOR [LevelId] IN ([1],[2],[3],[4],[5],[6],[7],[8])
) AS PivotTable
)
SELECT OrgId,[1] AS [Level 1 Org], [2] AS [Level 2 Org], [3] AS [Level 3 Org], [4] AS [Level 4 Org],
[5] AS [Level 5 Org], [6] AS [Level 6 Org], [7] AS [Level 7 Org], [8] AS [Level 8 Org]  FROM OrgSequence

No comments:

Post a Comment

My Blog List

  • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी संतान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
    3 months ago
  • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी शमशान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
    3 months ago
  • Kumaon University Nainital B.Ed entrance exam test result 2012 - कुमाऊँ विश्वविधालय, नैनीताल (उत्तराखण्ड)
    10 years ago