2017-10-18 132 views
0

我有需要,形成樹形結構的層次結構如下4個的結果集:如何排列在樹形結構的層次結構設置SQL結果

結果集:

  1. 學院
  2. HeadOfDepartment
  3. 老師
  4. 學生

現在的層次結構應如下:

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  
+0

我認爲SQL永遠不會給你層次結果。那麼表格格式的預期輸出是什麼。 –

+0

是表格格式! – Swetha

+0

添加了樣本數據和期望的輸出。不能格式化結果集:( – Swetha

回答

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

+0

謝謝!在這裏我正在尋找多套... – Swetha