sql排序问题求解本帖最后由 sefwhy 于 2013-09-04 18:15:08 编辑int idint tid1NULL2NULL3NULL4NULL5NULL6
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
/*
idtid
1NULL
81
2NULL
62
72
3NULL
93
4NULL
5NULL
*/
