27,579
社区成员
发帖
与我相关
我的任务
分享
with tb as
(
select ID=1,NAME='A',ID_PARENT=3 union all
select 2,'B',NULL union all
select 3,'C',5 union all
select 4,'D',NULL union all
select 5,'E',2 union all
select 6,'F',1
),
cte as(
select *, ID_GROUP=ID from tb where isnull(ID_PARENT,'')=''
union all
select tb.*,cte.ID_GROUP from cte,tb where cte.ID=tb.ID_PARENT
)
select * from cte order by id
;WITH CTE AS(
SELECT ID,[NAME],ID_PARENT,ID AS [ID_GROUP]
FROM TB
WHERE ID_PARENT IS NULL
UNION ALL
SELECT T1.ID,T1.[NAME],T1.ID_PARENT,T2.[ID_GROUP]
FROM TB T1
JOIN CTE T2 ON T1.ID_PARENT=T2.ID
)
SELECT * FROM CTE
ORDER BY ID
create table test(ID int,NAME varchar(10),ID_PARENT int)
insert into test
select 1, 'A', 3 union all
select 2, 'B', NULL union all
select 3, 'C', 5 union all
select 4, 'D', NULL union all
select 5, 'E', 2 union all
select 6, 'F', 1
go
create function fn_getUP(@id int)
returns int
as begin
declare @reID int
;with sel as
(select id,id_parent,0 as lev from test where id=@id
union all
select a.id,a.id_parent,b.lev+1 from test a
join sel b on a.id=b.id_parent)
select top (1) @reID=id from sel order by lev desc
return @reID
end
go
select id,name,id_parent,dbo.fn_getUP(id) as groupID from test
create table t
(
id int,
name varchar(100),
id_parent int
)
insert into t values (1,'A',3)
insert into t values (2,'B',null)
insert into t values (3,'C',5)
insert into t values (4,'D',null)
insert into t values (5,'E',2)
insert into t values (6,'F',1)
with f as
(
select id as constid, id ,name,id_parent ,0 as lev from t
union all
select b.constid, a.id ,a.name,a.id_parent,lev+1 from t as a inner join f as b on a.id=b.id_parent
)
select f1.id ,f1.name,f1.id_parent,f2.id as id_group from f f1,f f2 where f1.constid=f2.constid and f1.lev=0 and f2.id_parent is null;
id name id_parent id_group
----------- ---------------------------------------------------------------------------------------------------- ----------- -----------
1 A 3 2
2 B NULL 2
3 C 5 2
4 D NULL 4
5 E 2 2
6 F 1 2
(6 行受影响)