日期:2014-05-17  浏览次数:20463 次

sql排序问题求解
本帖最后由 sefwhy 于 2013-09-04 18:15:08 编辑
int id  int tid
1       NULL
2       NULL
3       NULL
4       NULL
5       NULL
6       2
7       2
8       1
9       3

如何排序成:
int id  int tid
1       NULL
8       1
2       NULL
6       2
7       2
3       NULL
9       3
4       NULL
5       NULL

tid是id的子的意思。

------解决方案--------------------
create table #tb( id int,  tid int)
insert into #tb
select 1,NULL
union all select 2,NULL
union all select 3,NULL
union all select 4,NULL
union all select 5,NULL
union all select 6,2
union all select 7,2
union all select 8,1
union all select 9,3

select *
from 
(select distinct a.*
from #tb a
left join #tb b on a.id=b.tid
)a
order by case when a.tid IS null then a.id else a.tid end,a.tid
drop table #tb

/*
id tid
1 NULL
8 1
2 NULL
6 2
7 2
3 NULL
9 3
4 NULL
5 NULL
*/