简体   繁体   English

SQL 服务器分层查询

[英]SQL Server hierarchical query

I have a table of users setup like this in SQL Server database我在 SQL 服务器数据库中有一个这样的用户设置表

UserID  ReportsToUserID
1        NULL
2        NULL
3        1
4        2
5        2
6        3
7        5
...

Is there a way in SQL where I can get all the employees on the reporting chain. SQL 中有没有办法让我可以让报告链上的所有员工。 For example when I supply 1, I am expecting to get employeesID 3,6例如,当我提供 1 时,我期望得到employeesID 3,6

When I supply 2 I am expecting 4,5,7当我提供 2 时,我期待4,5,7

I do not know max number of chain it can go under我不知道go下的最大链数

Here is a recursive CTE where you can set the @Top with either NULL for the entire hierarchy or with a specific UserID这是一个递归 CTE,您可以使用NULL为整个层次结构或使用特定的UserID设置@Top

Declare @YourTable Table ([UserID] int,[ReportsToUserID] int)
Insert Into @YourTable Values 
 (1,NULL)
,(2,NULL)
,(3,1)
,(4,2)
,(5,2)
,(6,3)
,(7,5)
 
Declare @Top int = null --<<  Sets top of Hier Try 1 or 2

;with cteP as (
      Select UserID
            ,ReportsToUserID 
            ,HierID = convert(hierarchyid,concat('/',UserID,'/'))
      From   @YourTable 
      Where  IsNull(@Top,-1) = case when @Top is null then isnull(ReportsToUserID ,-1) else UserID end
      Union  All
      Select UserID  = r.UserID
            ,ReportsToUserID  = r.ReportsToUserID 
            ,HierID = convert(hierarchyid,concat(p.HierID.ToString(),r.UserID,'/'))
      From   @YourTable r
      Join   cteP p on r.ReportsToUserID  = p.UserID)
Select R1    = Row_Number() over (Order By HierID)
      ,R2    = (Select count(*) From cteP where HierID.ToString() like A.HierID.ToString()+'%')
      ,Lvl   = HierID.GetLevel()
      ,UserID
      ,ReportsToUserID
      ,HierID_String = HierID.ToString()
 From cteP A
 Order By A.HierID

Returns退货

在此处输入图像描述

Now if @Top was set to 1现在如果 @Top 设置为 1

在此处输入图像描述

NOTE:笔记:

The columns R1, R1,Lvl and HierID_String are completely optional and demonstrative. R1, R1,Lvl and HierID_String是完全可选的和示范性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM