以下是记录最初存储在表格中的顺序:
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');
原始存储表:
必需的输出顺序:
我基本上在寻找没有游标或临时表的解决方案。派生表虽然很好
答案 0 :(得分:2)
您可以在coalesce
中使用order by
。
select * from locations
order by coalesce(parent,name),case when parent is null then 0 else 1 end,name
答案 1 :(得分:2)
我不确定为什么@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;