今天在CSDN看到个题目是关于树形在内容:
题目如下(但实际的题目更简单)
create table #t(id int,parentid varchar(10))
insert into #t
select 1, 0 union all
select 10, 1 union all
select 13, 10 union all
select 16, 10 union all
select 11, 16 union all
select 3, 0 union all
select 4, 3 union all
select 8, 4 union all
select 5, 3 union all
select 6, 5 union all
select 7, 3 union all
--输出结果
/*
id parentid
----------- ----------
1 0
10 1
13 10
16 10
11 16
3 0
4 3
8 4
5 3
6 5
7 3*/
看到题目后,我记得以前曾看到过类似的问题,并查看收集的资料,处理如下:
--处理内容
SELECT *
FROM #t a
LEFT JOIN #t b ON a.parentid=b.id
ORDER BY CASE
WHEN b.parentid IS NULL THEN a.id
WHEN b.parentid=0 THEN b.id
ELSE b.parentid END,
CASE
WHEN b.parentid=0 THEN a.id
ELSE a.parentid END,
a.id
--以上就是答案,但以上的查询是有条件的,就是递归的内容不超过三个(父子关系不超过三代)
--若递归多的话,怎么办呢?
--想了个办法就是利用以下语句完成。
with cte(id1,id,parentid)
as
(select cast(row_number() over(order by id) as varchar(10)) id1,*from #t where parentid=0
union all
select cast(id1+cast(row_number() over(order by a.id)as varchar(10)) as varchar(10)),a.* from #t a join cte on cte.id=a.parentid )
select id,parentid from cte order by id1
--特此标记12:09:05