SQL-按列表顺序排序 [英] SQL - order by list order

查看:146
本文介绍了SQL-按列表顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following query that returns rows based on a comma seperated list

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

我希望此查询的结果以列表中ID的顺序返回.使用SQL可以做到吗?

I would like the results of this query to return to in the order of the ID's in the list. Is that possible with SQL?

预先感谢

推荐答案

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

If you need the output to appear in a particular order, then you need to specify that order, using something the server can sort. Not knowing which engine you're working against, the general scheme would be to create a temp table or use rowset constructors to pair each record ID with its desired sort order.

例如(SQL Server)

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

这篇关于SQL-按列表顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆