SQL - 按列表顺序排序

时间:2011-07-07 10:27:50

标签: sql sql-server list

我有以下基于逗号分隔列表返回行的查询

Select * from Table where RecordID in (22,15,105,1,65,32)

我希望此查询的结果按照列表中ID的顺序返回。这可能与SQL有关吗?

提前致谢

6 个答案:

答案 0 :(得分:14)

select * from Table
where RecordID in (22,15,105,1,65,32)
order by (
    case RecordID 
        when 22 then 1
        when 15 then 2
        when 105 then 3
        when 1 then 4
        when 65 then 5
        when 32 then 6 end)

答案 1 :(得分:10)

如果您需要输出以特定顺序显示,则需要使用服务器可以排序的内容指定该顺序。不知道你正在使用哪个引擎,一般方案是创建临时表或使用行集构造函数将每个记录ID与其所需的排序顺序配对。

E.g。 (SQL Server)

declare @T table (RecordID int,Position int)
insert into @T (RecordID,Position)
select 22,1 union all
select 15,2 union all
select 105,3 union all
select 1,4 union all
select 65,5 union all
select 32,6

select * from Table t inner join @T t2 on t.RecordID = t2.RecordID order by t2.Position

答案 2 :(得分:2)

我要在客户端进行排序,但是如果你真的想在SQL中这样做,那就这样做:

declare @T table (id int identity(1,1), RecordID int)

insert into @T (RecordID)
values (22), (15), (105), (1), (65), (32)

select * from 
[table] t 
inner join @t s on t.id=s.recordid
where t.id in (22, 15, 105, 1, 65, 32)
order by s.id

(适用于SQL Server 2008)

答案 3 :(得分:0)

是。您可以在最后添加ORDER BY recordedid子句。

答案 4 :(得分:-1)

最后一次我必须这样做,我最终做了一个union all并为每个id生成一个select语句,即

select * from Table where RecordID = 22
union all
select * from table where recordid = 15

这很痛苦,但确实有效。

答案 5 :(得分:-3)

ORDER BY

使用RecordID
Select * from Table where RecordID in (22,15,105,1,65,32) ORDER BY RecordID 
相关问题