iho*_*rko 12 sql sql-server hierarchical-data sql-server-2008
我有一个树结构的表:
id parentId name
----------------
1 0 Category1
2 0 Category2
3 1 Category3
4 2 Category4
5 1 Category5
6 2 Category6
7 3 Category7
Run Code Online (Sandbox Code Playgroud)
在SQL查询resut我需要一个像这样的表:
id parentId level name
----------------------
1 0 0 Category1
3 1 1 Category3
7 3 2 Category7
5 1 1 Category5
2 0 0 Category2
4 2 1 Category4
6 2 1 Category6
Run Code Online (Sandbox Code Playgroud)
谁能帮我写ms-sql查询?谢谢!
a_h*_*ame 24
WITH tree (id, parentid, level, name) as
(
SELECT id, parentid, 0 as level, name
FROM your_table
WHERE parentid = 0
UNION ALL
SELECT c2.id, c2.parentid, tree.level + 1, c2.name
FROM your_table c2
INNER JOIN tree ON tree.id = c2.parentid
)
SELECT *
FROM tree;
Run Code Online (Sandbox Code Playgroud)
我目前没有SQL Server来测试它,因此可能存在一些拼写错误(语法错误)
Ric*_*iwi 24
扩大对a_horse_with_no_name的答案,这展示了如何使用SQL Server的执行递归CTE的(递归单记录的交叉应用组合)与ROW_NUMBER()来产生这个问题的准确输出.
declare @t table(id int,parentId int,name varchar(20))
insert @t select 1, 0 ,'Category1'
insert @t select 2, 0, 'Category2'
insert @t select 3, 1, 'Category3'
insert @t select 4 , 2, 'Category4'
insert @t select 5 , 1, 'Category5'
insert @t select 6 , 2, 'Category6'
insert @t select 7 , 3, 'Category7'
;
WITH tree (id, parentid, level, name, rn) as
(
SELECT id, parentid, 0 as level, name,
convert(varchar(max),right(row_number() over (order by id),10)) rn
FROM @t
WHERE parentid = 0
UNION ALL
SELECT c2.id, c2.parentid, tree.level + 1, c2.name,
rn + '/' + convert(varchar(max),right(row_number() over (order by tree.id),10))
FROM @t c2
INNER JOIN tree ON tree.id = c2.parentid
)
SELECT *
FROM tree
order by RN
Run Code Online (Sandbox Code Playgroud)
老实说,使用ID本身来生成树"路径"会起作用,因为我们直接按id排序,但我想我会在row_number()函数中滑动.