如何在树结构层次结构中对齐SQL结果集

时间:2017-10-18 11:48:47

标签: sql sql-server tree

我有4个结果集需要形成树结构层次结构,如下所示:

结果集:

  1. 学院
  2. HeadOfDepartment
  3. 教师
  4. 学生
  5. 现在层次结构应该如下:

    College1
       HeadOfDepartment1
           Teacher1
               Student1
               Student2
           Teacher2
               Student3
       HeadOfDepartment2
           Teacher3
               Student4
               Student5
           Teacher4
               Student6
    College2
    ............
    

    形成这种等级的可行解决方案是什么?  我已尝试row_number() over相应的组进行排序。
    示例数据

    ObjectID    Stream      Category    University  Percentage  Subject
    College1    Engineering             University1     
    College2    Medical                 University2  
                        ObjectID        Stream      Category    University  Percentage  Subject
    Belongs to College1 HOD1        Management          
    Belongs to College1 HOD2        Technical           
    
                    ObjectID    Stream  Category    University  Percentage  Subject
    Belongs to HOD1 Teacher1                                                SQL  
    Belongs to HOD2 Teacher2                                                Java
    
                        ObjectID    Stream  Category    University  Percentage  Subject 
    Belongs to Teacher1 Student1                                            90  SQL  
    Belongs to Teacher2 Student2                                            80  Hibernate  
    

    期望输出:

    ObjectID    Stream      Category       University   Percentage  Subject 
    College1    Engineering                University1      
    HOD1        Management              
    Teacher1                                                        SQL  
    Student1                                            90          SQL  
    HOD2        Technical       
    Teacher2                                                        Java  
    Student2                                            80          Hibernate 
    College2    Medical                    University2      
    

1 个答案:

答案 0 :(得分:0)

使用union all的方法是:

;with combination as (
    -- Colleges
    select cast(id as char(5)) id,
        [name]
    from College
    union all 
    -- HeadOfDepartments
    select cast(CollegeId as char(5)) + cast(id as char(5))
        , '    ' + [name]
    from HeadOfDepartment
    union all
    -- Teachers
    select cast(h.CollegeId as char(5)) + cast(h.id as char(5)) + cast(t.id as char(5))
        , '        ' + t.[name]
    from Teacher t
    join HeadOfDepartment h 
      on t.HeadOfDepartmentId = h.id
    union all 
    -- Students
    select cast(h.CollegeId as char(5)) + cast(h.id as char(5)) + cast(t.id as char(5)) + cast(s.id as char(5))
        , '            ' + s.[name]
    from Student s
    join Teacher t
      on s.TeacherId = t.id
    join HeadOfDepartment h 
      on t.HeadOfDepartmentId = h.id
)
select [name]
from combination
order by id;

SQL Fiddle Demo