我正在运行一个相当长的SQL查询,它的核心是非常基本的:
SELECT * FROM documents WHERE doc_id IN (995,941,940,954,953,973)这个查询的目标结果是按照在in子句中设置的顺序显示文档。然而,我还没有找到一个干净的解决方案来这样做。
我想我可以使用charindex()来处理这个问题。
ORDER BY charindex('995,941,940,954,953,973',doc_id)order BY的结果只是按照默认的ASC顺序对doc_ids进行排序。
关于如何明确定义此查询的结果顺序,有什么指导意见吗?
发布于 2013-02-26 01:03:02
您的charindex是反向的:
order by charindex(doc_id, '995,941,940,954,953,973')如果doc_id存储为数字,则需要进行强制转换:
order by chardindex(cast(doc_id as varchar(255)), '995,941,940,954,953,973')而且,您可以考虑将文档in放在一个列表中。然后可以在整个查询中使用它们:
with doclist as (
select 1 as ordering, '995' as docid union all
select 2 , '941' union all
. . .
)
select . . .
from . . .
left outer join
doclist dl
on docid = dl.docid
order by dl.orderinghttps://stackoverflow.com/questions/15072246
复制相似问题