我在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.重要的一点是在上面的结果中显示每行的第一个节点到最后一个节点的代码连接,就像上面的newcolumn一样,实际上我不能产生新的列? *注意节点级别是无限的。
答案 0 :(得分:4)
使用recursive common table expressions:
可以相对轻松地完成此操作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 强>