sql服务器使用递归cte获取同组关卡
sql server using recrusive cte to get the level in the same group
我有一个 sql 服务器 table 显示 ID 和他们以前的 ID,
create table test2 ( ID varchar(10) ,
Pre_ID varchar(10)
)
insert into test2 values ('e','d')
, ('d','c')
, ('c','b')
, ('b','a')
, ('a',null)
, ('r','q')
, ('q','p')
, ('p',null)
table是这样的:
结果应该是这样的:
我已经使用递归 cte 成功获得关卡,但无法为它们获得正确的组。谁能帮忙?谢谢。
这是我的代码:
with cte as (
select id, Pre_ID, level
from #temp2
where Pre_ID is null
union all
select t2.id, t2.Pre_ID, t2.level
from cte
inner join #temp2 t2
on t2.Pre_ID=cte.id
)
select * from cte
order by id
您需要做的是从第一个级别开始并向其添加 ROW_NUMBER
,然后递归加入所有其他级别:
with cte as (
select id, Pre_ID, level, row_number() over (order by ID) as grp
from #temp2
where Pre_ID is null
union all
select t2.id, t2.Pre_ID, t2.level, cte.grp
from cte
inner join #temp2 t2
on t2.Pre_ID=cte.id
)
select * from cte
order by id;
我有一个 sql 服务器 table 显示 ID 和他们以前的 ID,
create table test2 ( ID varchar(10) ,
Pre_ID varchar(10)
)
insert into test2 values ('e','d')
, ('d','c')
, ('c','b')
, ('b','a')
, ('a',null)
, ('r','q')
, ('q','p')
, ('p',null)
table是这样的:
结果应该是这样的:
我已经使用递归 cte 成功获得关卡,但无法为它们获得正确的组。谁能帮忙?谢谢。
这是我的代码:
with cte as (
select id, Pre_ID, level
from #temp2
where Pre_ID is null
union all
select t2.id, t2.Pre_ID, t2.level
from cte
inner join #temp2 t2
on t2.Pre_ID=cte.id
)
select * from cte
order by id
您需要做的是从第一个级别开始并向其添加 ROW_NUMBER
,然后递归加入所有其他级别:
with cte as (
select id, Pre_ID, level, row_number() over (order by ID) as grp
from #temp2
where Pre_ID is null
union all
select t2.id, t2.Pre_ID, t2.level, cte.grp
from cte
inner join #temp2 t2
on t2.Pre_ID=cte.id
)
select * from cte
order by id;