层次结构查询中从父级到子级的T-SQL排序数据



我有分层数据,包括父母和孩子以及位置。

样品:

create table groups 
(
Child varchar(1), 
Parent varchar(1), 
Position int
);
insert into groups (Child, Parent, Position) 
values ('A', NULL, 1),
('B', 'A', 1),
('C', 'B', 1),
('D', 'B', 2),
('E', NULL, 2),
('F', NULL, 3),
('G', 'F', 1),
('H', 'G', 1),
('I', 'G', 2),
('J', 'F', 2),
('K', 'J', 1),
('L', 'J', 2);

每个组和子组都有自己的位置,从1开始,例如:

  • 所有父母都有位置:1-x
  • 所有有父母的孩子";A";具有位置:1-x
  • 所有有父母的孩子";N〃;具有位置:1-x

我需要按照父母的孩子总是在父母之间升序排列查询,例如(为了更好的想象力而增加级别(:

Level|Child|Parent|Position
-----+-----+------+---------
3  |  A  | NULL |   1
2  |  B  |   A  |   1
1  |  C  |   B  |   1
1  |  D  |   B  |   2
3  |  E  | NULL |   2
3  |  F  | NULL |   3
2  |  G  |   F  |   1
1  |  H  |   G  |   1
1  |  I  |   G  |   2
2  |  J  |   F  |   2
1  |  K  |   J  |   1
1  |  L  |   J  |   2

这是我当前的代码:

;with cte as 
(
select Child, Parent, Position 
from groups
union all
select t.Child, t.Parent, t.Position 
from groups t
join cte on t.Child = cte.Parent
)
select distinct * 
from cte 
order by Position

db<gt;小提琴示例

谢谢

您的cte有点乱。我会这样做:

;with cte as (
select Child, Parent, Position As ParentPosition, Position, 1 As level 
from groups
where parent is null
union all
select t.Child, t.Parent, cte.ParentPosition, t.Position, level + 1
from groups AS t
join cte on t.Parent = cte.Child
)
select  * 
from cte 
order by ParentPosition, level, Position

cte的锚定部分是表中的所有记录,实际上它应该只是没有父级的记录(因此是where parent is null(
此外,我还为父级的位置添加了一列,以便在下一个父级之前对同一父级的所有子级进行排序,并添加了一个级别列,以帮助按与主父级的距离排序子级。

结果:

Child   Parent  ParentPosition  Position    level
A               1               1           1
B       A       1               1           2
C       B       1               1           3
D       B       1               2           3
E               2               2           1
F               3               3           1
G       F       3               1           2
J       F       3               2           2
K       J       3               1           3
H       G       3               1           3
I       G       3               2           3
L       J       3               2           3

Db<gt;Fiddle

最新更新