34,590
社区成员
发帖
与我相关
我的任务
分享
with tb(id,pid)
as
(
select 1, 4 union all
select 2, 1 union all
select 3, 6 union all
select 4, NULL union all
select 5, 1 union all
select 6, 8 union all
select 7, 9 union all
select 8, 9 union all
select 9, 1 union all
select 11, 2
),
tb1(id,pid,[level]) AS(
SELECT id,pid,0 FROM tb WHERE pid IS NULL
UNION ALL
SELECT tb.id,tb.pid,tb1.[level]+1 FROM tb,tb1 WHERE tb.pid = tb1.id
)
SELECT * FROM tb1 ORDER BY level
这个最多再加个LEVEL, 如果要像oracle那样,恐怕CTE做不到,需要用到临时表处理吧with tb(id,pid)
as
(
select 1, 4 union all
select 2, 1 union all
select 3, 6 union all
select 4, NULL union all
select 5, 1 union all
select 6, 8 union all
select 7, 9 union all
select 8, 9 union all
select 9, 1
),
tb1 as
(
select id,pid from tb where pid is null
union all
select b.id,b.pid from tb1 a,tb b where a.id=b.pid
)
select * from tb1