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 which retrives me last node?(我通过以下行做了)

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.重要的是在上面的结果中显示从每行的第一个节点到最后一个节点的代码连接,就像上面的newcolumn,实际上我不能产生newcolumn?*请注意,节点级别是无限的。

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 回答