SQL 按指定顺序进行排序

在有些情况下我们需要按指定顺序输出数据,比如选择了ID in(3,1,2,5,4)我们希望按这个3,1,2,5,4的顺序输出,这样只使用order by ID是无法实现的,但是我们可以使用order by charindex(','+convert(varchar,ID)+',',',3,1,2,5,4,')的方法来实现这个目的。举例如下:

Create Table info(

ID int identity(1,1) not null,

title varchar(100) not null

)

select id,title

from info

where id in ('3,1,2,5,4')

order by charindex(','+convert(varchar,ID)+',',',3,1,2,5,4,')