我在Microsoft SQL Server 2008中使用T / SQL
我有一张桌子
CREATE TABLE [TestTable](
[CHILD] [int] NOT NULL,
[PARENT] [int] NOT NULL
) ON [PRIMARY]
GO
这些是定义父子层次关系的一些值
CHILD PARENT
1 2
2 0
3 1
4 2
5 0
从视觉上看,这个表格看起来像这样
0
2
1
3
4
5
我理想地将值显示如下(右侧列表示生成)
CHILD GENERATION
0 0
2 1
1 2
3 3
4 2
5 1
我的T / SQL代码如下所示
with n(CHILD, PARENT, GENERATION) as (
select CHILD, PARENT,1 as GENERATION from TestTable
where PARENT=0
union all
select nplus1.CHILD, nplus1.PARENT, GENERATION+1 from TestTable as nplus1, n
where nplus1.PARENT=n.CHILD
)
select CHILD,GENERATION from n
然而它不起作用!
返回
CHILD GENERATION
2 1
5 1
1 2
4 2
3 3
它有正确的一代,但错误的排序顺序! 有没有人有任何想法如何解决这个问题?
谢谢!
答案 0 :(得分:6)
你需要你的递归来构建一些可以在最后排序的东西:
declare @t TABLE (
[CHILD] [int] NOT NULL,
[PARENT] [int] NOT NULL
)
insert @t values
( 0, -1), -- I added this
( 1, 2 ),
( 2, 0 ),
( 3, 1 ),
( 4, 2 ),
( 5, 0 )
(注意我添加了一个真正的根元素)
;with n(CHILD, PARENT, GENERATION, hierarchy) as (
select CHILD, PARENT,0, CAST(CHILD as nvarchar) as GENERATION from @t
where PARENT=-1
union all
select nplus1.CHILD, nplus1.PARENT, GENERATION+1,
cast(n.hierarchy + '.' + CAST(nplus1.child as nvarchar) as nvarchar)
from
@t as nplus1 inner join n on nplus1.PARENT=n.CHILD
)
select CHILD,GENERATION
from n
order by hierarchy
返回
CHILD GENERATION
----------- -----------
0 0
2 1
1 2
3 3
4 2
5 1
包括hierarchy
以供说明:
CHILD GENERATION hierarchy
----------- ----------- ------------------------------
0 0 0
2 1 0.2
1 2 0.2.1
3 3 0.2.1.3
4 2 0.2.4
5 1 0.5
根据你的id有多大,你可能不得不用零填充左边填充来正确排序。
请注意,SQL 2008有这种内置的hierarchy
类型...
答案 1 :(得分:0)
基于AakashM的解决方案,我提出的解决方案将更加通用,因为它使用row_number来构建层次结构 而不是使用列值。
就是这样:
;with n(CHILD, PARENT, GENERATION, hierarchy) as (
select CHILD, PARENT,0, CAST(CHILD as nvarchar) as GENERATION from @t
where PARENT=-1
union all
select nplus1.CHILD, nplus1.PARENT, GENERATION+1,
cast(hierarchy + '.' + CAST(cast(ROW_NUMBER() over (order by nplus1.CHILD) as int) as nvarchar) as nvarchar)
from
@t as nplus1 inner join n on nplus1.PARENT=n.CHILD
)
select CHILD,GENERATION,hierarchy
from n
order by hierarchy
返回:
CHILD GENERATION hierarchy
0 0 0
2 1 0.1
1 2 0.1.1
3 3 0.1.1.1
4 2 0.1.2
5 1 0.2