按where子句中的指定排序查询结果

时间:2015-05-29 06:09:42

标签: sql-server-2008

我有一张表QuotesTable - 主键是quotesid

我有sql-statement

 select * from QuotesTable where quotesid in (103,7,16,50,41,80,67,64)

这将按以下顺序返回结果:

 7
 16
 41
 .........
 103 and so on. 

但我需要按照查询(103,7,16,50,41,80,67,64)中指定的顺序执行结果:

 103,
 7
 16
 .......
 64 and so on.

有没有办法实现这个?

2 个答案:

答案 0 :(得分:4)

试试这个:

select * from QuotesTable where quotesid in (103,7,16,50,41,80,67,64)
order by case quotesid when 103 then 1
                       when  7  then 2
                       when 16  then 3
                       when 50  then 4
                       when 41  then 5
                       when 80  then 6
                       when 67  then 7
                       when 64  then 8
         end

如果这些值增长,那么您可以在数据库中创建一个表:

create table QuotesOrderingTable(quotesid int, orderid int)
go

用适当的值填充它:

insert into QuotesOrderingTable values
(103, 1),
(7, 2),
(16, 3),
(50, 4),
(41, 5),
(80, 6),
(67, 7),
(64, 8),
(..., 9),
(..., 10),
...

然后用它来订购:

select qt.* from QuotesTable qt
join QuotesOrderingTable qot on qt.quotesid = qot.quotesid
where qt.quotesid in (103,7,16,50,41,80,67,64)
order by qot.orderid

答案 1 :(得分:0)

另一个选择是这样做:

SELECT * FROM QuotesTable q
JOIN (SELECT 1 ordering, 103 quotesid UNION ALL
      SELECT 2         , 7 UNION ALL
      SELECT 3         , 16 UNION ALL
      SELECT 4         , 50 UNION ALL
      SELECT 5         , 41 UNION ALL
      SELECT 6         , 80 UNION ALL
      SELECT 7         , 67 UNION ALL
      SELECT 8         , 64) o ON o.quotesid = q.quotesid
ORDER BY o.ordering

不是最漂亮的,但至少你没有重复WHERE子句

另一种变化,看起来更好一点:

:nth-of-type(2)