order by常用的使用方式我就不提了
项目的需求千变万化
让我们看看下面几个怪排序需求
--先创建一个表
create table ai(
id int not null,
no varchar(10) not null
)
go
--往表中插入数据
insert into ai
select 105,'2'
union all
select 105,'1'
union all
select 103,'1'
union all
select 105,'4'
go
--查询效果如下:
select * from ai
go
id no
----------- ----------
105 2
105 1
103 1
105 4
i.
--要求的查询结果如下
--即要求no列的数据按'4','1','2'排列
id no
----------- ----------
105 4
105 1
103 1
105 2
--解决方案1
--利用函数CHARINDEX
select * from ai
order by charindex(no,'4,1,2')
--解决方案2,并且每组再按照id降序排列
--利用函数case
select * from ai
order by case when no='4' then 1
when no='1' then 2
when no='2' then 3
end,id desc