1

私はSQLでこのテーブルを持っています:

TopicID      Code       Name       ParentID
-------      ----       ----       --------
1            001        Parent1       0
2            001        Childp1       1
3            002        Parent2       0
4            001        Childp2       3
5            001        Childp21      4
.
.
etc

今、私は最後のノードを取得する 1.get sql select をしたいですか? (私は次の行で行いました)

select * from accounting.topics where topicid not in(select parentid from accounting.topics)

結果は次のとおりです。

TopicID      Code       Name       ParentID  |    newcolumn
-------      ----       ----       --------  |   ---------
2            001        Childp1       1      |    001001
5            001        Childp21      4      |    002001001

2.重要なのは、上記の結果の各行の最初のノードから最後のノードまでのコードの連結を表示することです。*ノードレベルは無制限であることに注意してください。

4

1 に答える 1

4

これは、再帰的な共通テーブル式を使用すると比較的簡単に実行できます。

with cte as (
    select
        T1.TopicID, T1.Code, T1.Name, T1.ParentID,
        T1.ParentID as NewParentID,
        cast(T1.Code as nvarchar(max)) as NewColumn
    from Table1 as T1
    where not exists (select * from Table1 as T2 where T2.ParentID = T1.TopicID)
    union all
    select
        c.TopicID, c.Code, c.Name, c.ParentID,
        T1.ParentID as NewParentID,
        c.NewColumn + cast(T1.Code as nvarchar(max)) as NewColumn
    from cte as c
        inner join Table1 as T1 on T1.TopicID = c.NewParentID
)
select
    c.TopicID, c.Code, c.Name, c.ParentID, c.NewColumn
from cte as c
where c.NewParentID = 0

sql fiddle demo

于 2013-09-17T08:07:40.847 に答える