0

我有以下数据集

Create table #table(
Message varchar(10),
ID varchar(5),
ParentID varchar(5))


Insert into #table 
select 'Parent','123',''
UNION
select 'Child','234','123'
UNION
select 'Child','345','123'
UNION
select 'Child','145','123'
UNION
select 'Parent','333',''
UNION
select 'Child','567','333'
UNION
select 'Child','789','333'
UNION
select 'Child','100','333'
UNION
select 'Child','111','333'

select * from #table

当我选择数据时,数据看起来是随机的。但我想按以下顺序

Message    ID      ParentID
Parent     123     
Child      234     123
Child      345     123
Child      145     123 
Parent     333     
Child      567     333
Child      789     333
Child      100     333 
Child      111     333 

我尝试使用 row number ,它不适用于以下序列。有人可以帮帮我吗 ?

4

3 回答 3

1

使用中的CASE语句ORDER BY,以下查询应该执行您想要的操作:

select * from #table
order by case when Message = 'Parent' then ID else ParentID end, ParentID
于 2019-08-21T13:30:34.303 回答
0

用这个:

select message,id,parentid
from  #table
order by case when parentid = '' then convert(int,id)-1 else parentid end

此解决方案不基于消息列,并且将纠正所有数据集。

于 2019-08-21T13:34:13.027 回答
0

使用条件排序:

select * from #table
order by case when parentid = '' then id else parentid end, parentid

请参阅演示
结果:

> Message | ID  | ParentID
> :------ | :-- | :-------
> Parent  | 123 |         
> Child   | 145 | 123     
> Child   | 234 | 123     
> Child   | 345 | 123     
> Parent  | 333 |         
> Child   | 100 | 333     
> Child   | 111 | 333     
> Child   | 567 | 333     
> Child   | 789 | 333  

如果父项包含NULLatparentid列而不是'',则该ORDER BY子句必须更改为:

order by isnull(parentid, id), parentid
于 2019-08-21T13:36:47.267 回答