以下是记录最初存储在表中的顺序:
CREATE TABLE Locations
(
Name varchar(255),
Description varchar(255),
Parent varchar(255)
);
insert into locations values('L1','Parent Locaton1',null);
insert into locations values('SLC','Sub location B','L1');
insert into locations values('L2','Parent Locaton2',null);
insert into locations values('SLY','Sub Location Y','L2');
insert into locations values('SLZ','Sub Location Z','L2');
insert into locations values('SLA','Sub location A','L1');
insert into locations values('SLB','Sub location B','L1');
原始存储表:
要求的输出顺序:
我基本上是在寻找一种没有游标或临时表的解决方案。派生表虽然很好
最佳答案
我不确定为什么@vkp 删除了答案。它似乎对您的数据是正确的,除非您的层次结构中有多个级别:
select l.*
from locations l
order by coalesce(l.parent, l.name), name;
更具体地说,如果您想让父级始终排在第一位,您可能不想依赖名称:
select l.*
from locations l
order by coalesce(l.parent, l.name),
(case when l.parent is null then 1 else 2 end),
name;
关于sql - 如何从存储在MS SQL server表中的以下数据中获取结果集中的以下顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45202303/