簡體   English   中英

父/子層次結構樹視圖

[英]Parent/Child hierarchy tree view

我有一個父母表看起來像這樣

CHILD_ID | PARENT_ID | NAME
1        | Null      | Bill
2        | 1         | Jane
3        | 1         | Steve
4        | 2         | Ben
5        | 3         | Andrew

我喜歡得到這樣的結果集

Bill
---Jane
------Ben
---Steve
------Andrew

我知道我需要做一個排名查詢來排名水平和自我加入,但我能在網上找到的只是CTE遞歸

我以前在Oracle中完成了這個,但在MS SQL中沒有

有點hacky,可以改進,但希望它顯示原則......

;with relation (childId, parentId, childName, [level], [orderSequence])  
as  
(  
select childId, parentId, childName, 0, cast(childId as varchar(20))  
from @parents  
where parentId is null  
union all  
select p.childId, p.parentId, r.[level]+1, cast(r.orderSequence + '_' + cast(p.childId as varchar) as varchar(20))  
from @parents p  
inner join relation r on p.parentId = r.childId  
)  

select right('----------', ([level]*3)) +childName  
from relation  
order by orderSequence

但是,如果您想避免遞歸,那么另一種方法是使用相關的樹結構信息實現樹表 - 請參閱http://www.sqlteam.com/article/more-trees-hierarchies-in-sql以了解詳細信息

declare @pc table(CHILD_ID int, PARENT_ID int, [NAME] varchar(80));
 
insert into @pc
select 1,NULL,'Bill' union all
select 2,1,'Jane' union all
select 3,1,'Steve' union all
select 4,2,'Ben' union all
select 5,3,'Andrew' union all
select 6,NULL,'Tom' union all
select 7,8,'Dick' union all
select 8,6,'Harry' union all
select 9,3,'Stu' union all
select 10,7,'Joe';
 
 
; with r as (
      select CHILD_ID, PARENT_ID, [NAME], depth=0, sort=cast(CHILD_ID as varchar(max))
      from @pc
      where PARENT_ID is null
      union all
      select pc.CHILD_ID, pc.PARENT_ID, pc.[NAME], depth=r.depth+1, sort=r.sort+cast(pc.CHILD_ID as varchar(30))
      from r
      inner join @pc pc on r.CHILD_ID=pc.PARENT_ID
      where r.depth<32767
)
select tree=replicate('-',r.depth*3)+r.[NAME]
from r
order by sort
option(maxrecursion 32767);

這是一個艱難的:)。 我將示例擴展為包含> 1樹。 結果到目前為止看起來不錯

WITH DirectReports (ParentUniqId, UniqId, SortID)
AS
(
    SELECT e.ParentUniqId, e.UniqId, e.UniqId as SortID
    FROM Coding.Coding AS e
    WHERE isnull(ParentUniqId ,0)=0
    UNION ALL
    SELECT e.ParentUniqId, e.UniqId,, d.SortID * 100 + e.UniqId  as SortID
    FROM Coding.Coding AS e
    INNER JOIN DirectReports AS d
        ON e.ParentUniqId = d.UniqId

)
SELECT ParentUniqId, Perfix,SortID
FROM DirectReports order by rtrim(SortID) , uniqid

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM