如何使用sql查询创建路径

时间:2014-11-23 10:55:55

标签: sql sql-server

什么是最佳解决方案: 我在sqlserver中有一个包含这些内容的表。

PARENT CHILD  Level 
A        B      0
B        C      1
C        D      2
D        E      3

我需要一个查询来创建这个结果: A / B / C / d / E

2 个答案:

答案 0 :(得分:1)

您可以使用递归CTE:

with cte as (
       select t.parent as p, t.parent as c, 0 as lev
       from table t
       where not exists (select 1 from t t2 where t2.child = t.parent)
       union all
       select cte.p, t.child, lev + 1
       from cte join
            table t
            on cte.c = t.parent
     )
select stuff((select '/' + cte2.c
              from cte cte2
              where cte2.p = cte.p
              order by cte2.lev
              for xml path ('')
             ), 1, 1, '') as path
from cte
group by cte.p;

Here是一个SQL小提琴。

答案 1 :(得分:0)

使用Coalesce将行组合成单个列,用'/'分隔符

分隔
DECLARE @path VARCHAR(8000) = (SELECT parent FROM test WHERE LEVEL = 0)

SELECT @path = COALESCE(rtrim(@path) + '/', '') + child FROM test

SELECT @path