当前位置: 代码迷 >> Sql Server >> 请问SQL 排序有关问题
  详细解决方案

请问SQL 排序有关问题

热度:42   发布时间:2016-04-24 10:03:43.0
请教SQL 排序问题
比如两列id 和 numb,
id       numb
1        10
2        11
3        12
4        13
5        14
6        15
7        16
8        17
9        18
10      19



怎样让他按照大于等于15的排到前边按照正序,小于15的排到后边(按ID倒序)
结果如下:15,16,17,18,19,14,13,12,11,10


------解决方案--------------------
if object_id('[tb1]') is not null drop table [tb1]
go
create table tb1 (id int,numb int )
insert into tb1

select 1,10    union all                             
select 2,11    union all                             
select 3,12    union all                             
select 4,13    union all                             
select 5,14    union all                             
select 6,15    union all                             
select 7,16    union all                             
select 8,17    union all                             
select 9,18    union all                             
select 10,19                                         

go

select id ,numb  from 
(
select id ,numb,1 as s from tb1 where numb>=15
union all
select id ,numb,0 as s from tb1 where numb<15 
)
t  order by s desc, (case when  s=1 then numb end) asc ,(case when  s=0 then numb end) desc

--id numb
--6 15
--7 16
--8 17
--9 18
--10 19
--5 14
--4 13
--3 12
--2 11
--1 10
  相关解决方案