是否可以制作一个 ORDER BY 子句来确保两个字段(均为 INT 类型)的以下标准,称为 child
和 parent
分别为本例。
parent
引用 child
,但可以为空。 child
的每个值必须出现在 parent
之前在有序结果集中。 我对第 5 点有困难。
样本无序数据:
child parent
------------
1 NULL
3 5
4 2
2 5
5 NULL
显然不是
ORDER BY a, b
或 ORDER BY b, a
工作。事实上,我想得越多,我都不确定它甚至可以做到。鉴于这些限制,明显的情况例如:child parent
------------
1 2
2 1
不允许,因为它违反了规则 3 和 4(显然是 5)。
那么,我正在努力实现的目标是否可能,如果是,如何实现?平台为 SQL Server 2005。
更新:样本数据所需的排序顺序:
child parent
------------
1 NULL
5 NULL
2 5
3 5
4 2
对于在父列中定义非空值的每一行,该值已经存在于子列中。
最佳答案
您可以使用递归 CTE 来查找每个节点的“深度”,并以此排序:
create table node (id int, parent int)
insert into node values (1, null)
insert into node values (2, 5)
insert into node values (3, 5)
insert into node values (4, 2)
insert into node values (5, null)
insert into node values (6, 4);
with node_cte (id, depth) as (
select id, 0 from node where parent is null
union all
select node.id, node_cte.depth + 1
from node join node_cte on node.parent = node_cte.id
)
select node.*
from node
join node_cte on node_cte.id=node.id
order by node_cte.depth asc
关于sql - 复杂的 TSQL order by 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3179010/