如何从存储在MS SQL server表中的以下数据中获取结果集中的以下顺序?

时间:2017-07-19 22:49:39

标签: sql sql-server database sql-server-2012

以下是记录最初存储在表格中的顺序:

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'); 

原始存储表:

Original Table

必需的输出顺序:

enter image description here

我基本上在寻找没有游标或临时表的解决方案。派生表虽然很好

2 个答案:

答案 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;