以水平方式显示CTE中的层次结构信息

时间:2013-10-17 07:03:28

标签: sql sql-server-2008

我在SQl中写过CTE,它返回Hierarchy信息,如下所示: -

         Ecode          Name           RoleID         ImmediateSupervisor       
            21441          Dharm          1          20479         
            20479          Sri        2          21567         
            21567          Ram        3          21111         
            21111          Anand          4          21134         
            21134          Raghu          5          Null          
            20182          Subbu          4          21134         
            21465          Deepak         4          21134         
            21131          Ajay           3          21465         
            31234          Kalyan         1          21131         
            21141          Hemanth        1          20479         
            25478          Mahesh         1          21567         
            45698          Laxman         1          20182         
                                                            

我想以水平方式在水平方式中显示结果,如下所示: -

RoleID->    5   4   3   2   1
    Raghu   Anand   Ram     Mahesh
    Raghu   Anand   Ram Sri Dharm
    Raghu   Anand   Ram Sri Hemanth
    Raghu   Subbu           Laxman
    Raghu   Deepak  Ajay        Kalyan


在结果中,它按照RoleID以水平方式显示层次结构信息。 如果它们是任何跳过,那么该RoleID列将为空白。例如,您可以看到Laxman(RoleID-1)正在向Subbu报告(RoleID-4)。他们不是其他用户介于laxman和Subbu之间,所以结果空白是他们的For Column 3和2列。

请帮助我了解如何在SQl中实现这一目标。

1 个答案:

答案 0 :(得分:0)

您可以将查询编写为:

select 
T1.Name as [1],
    case 2 
    when T2.RoleID then T2.Name  
    when T3.RoleID then T3.Name 
    when T4.RoleID then T4.Name 
    when T5.RoleID then T5.Name 
    else null end as [2] ,
    case 3 
    when T2.RoleID then T2.Name  
    when T3.RoleID then T3.Name 
    when T4.RoleID then T4.Name 
    when T5.RoleID then T5.Name 
    else null end as [3] ,
    case 4
    when T2.RoleID then T2.Name  
    when T3.RoleID then T3.Name 
    when T4.RoleID then T4.Name 
    when T5.RoleID then T5.Name 
    else null end as [4] ,
    case 5
    when T2.RoleID then T2.Name  
    when T3.RoleID then T3.Name 
    when T4.RoleID then T4.Name 
    when T5.RoleID then T5.Name 
    else null end as [5] 
from table1 T1
left join table1  T2 on T1.ImmediateSupervisor  = T2.Ecode 
left join table1  T3 on T2.ImmediateSupervisor  = T3.Ecode 
left join table1  T4 on T3.ImmediateSupervisor  = T4.Ecode 
left join table1  T5 on T4.ImmediateSupervisor  = T5.Ecode 
where T1.RoleID = 1

希望这有帮助!!!