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

简单sql问题,给分50
select id ,name from user where id in(1,3,2,4) 
sqlserver 查询结果默认按id asc 排序了
 我想不按照它默认排序且就按照我给的id顺序排序(1324)该怎么写?
标准sql的写法其他数据库也的适应

------解决方案--------------------
select id ,name from user where id in(1,3,2,4)
order by charindex( ltrim(id) ,'1,3,2,4')
------解决方案--------------------
SQL code

select id ,name from user where id in(1,3,2,4)  order by case when 1 then 1 when 3 then 2 when 2 then 3 when 4 then 4 end
--try

------解决方案--------------------
前后都加引号
避免1 12 这种。
SQL code
select id ,name from user where id in(1,3,2,4)   
order by charindex( ','+ltrim(id)+',' ,',1,3,2,4,')

------解决方案--------------------
SQL code

select name,number from master..spt_values  where number in(1,2,3,4) and type='p'
order by case when number=1 then 1 
when number=3 then 2 when number=2 then 3 when number=4 then 4 end

/*
name                                number
----------------------------------- -----------
NULL                                1
NULL                                3
NULL                                2
NULL                                4

(4 行受影响)
*/

------解决方案--------------------
select id ,name from user where id in(1,3,2,4) order by (id+1)%2,id 

------解决方案--------------------
SQL code
select
   id ,name 
from [user] where id in(1,3,2,4)   
order by charindex( ','+ltrim(id)+',' ,',1,3,2,4,')