日期:2014-05-18  浏览次数:20480 次

求助看似简单的sql排序
比如存在一个表A 数据如下
A
1
2
3
4
5

我需要排序得出以下的结果
A
1
4
2
3
5

请问这样子如何想,我想了很久也想不出.

------解决方案--------------------
/*
比如存在一个表A 数据如下
A
1
2
3
4
5
我需要排序得出以下的结果
A
1
4
2
3
5
请问这样子如何想,我想了很久也想不出.
*/
go
if OBJECT_ID('tbl') is not null
drop table tbl
go
create table tbl(
A int
)
go
insert tbl
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5

select *from tbl
order by 
case A when 1 then 1 
when 4 then 2 
when 2 then 3 
when 3 then 4 
when 5 then 5 end
/*
结果:
A
1
4
2
3
5
*/
------解决方案--------------------
SQL code

declare @T table (A int)
insert into @T
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5

select * from @T order by charindex(ltrim(A),'14235')
/*
A
-----------
1
4
2
3
5
*/