按where子句匹配的顺序排序SQL查询

时间:2014-05-02 14:46:41

标签: sql sql-server-2008 sql-server-2005

SELECT 
    ProcductCode AS Id, 
    ProductPrice AS Price
FROM 
    Products WITH (NOLOCK)
WHERE 
    ProductCode = 'efg' OR ProductCode = 'abc' OR  ProductCode = 'xyz'

在上面的查询中,我希望按ProductCode顺序返回数据,但不是默认的升序或降序,而是由where子句找到匹配的顺序。

我不想要

ORDER BY ProductCode ASC|DESC; 

所以在上面的例子中,如果我们假设表子中有一个ProductCode条目,那么它应该返回

ID             Price
---------------------
efg            1.00
abc            1.00  
xyz            1.00

有没有办法通过“或”订单来订购。有点坚持这个。想法和/或示例会有所帮助

2 个答案:

答案 0 :(得分:4)

您可以使用case。使用where

更容易阅读in子句
SELECT ProcductCode AS Id, ProductPrice AS Price
FROM Products WITH (NOLOCK)
WHERE ProductCode IN ('efg', 'abc', 'xyz')
ORDER BY (CASE WHEN ProductCode = 'efg' THEN 1
               WHEN ProductCode = 'abc' THEN 2
               WHEN ProductCode = 'xyz' THEN 3
               ELSE 4  -- in case you change the `where`, put them last
          END);

顺便说一句,如果你想,你可以这样做:

ORDER BY CHARINDEX(','+ProductCode+',',
                   ',efg,abc,xyz,'
                  )

答案 1 :(得分:1)

ORDER BY CASE WHEN ProcductCode  = 'efg' THEN 1 
              WHEN ProcductCode  = 'abc' THEN 2
              WHEN ProcductCode  = 'xyz' THEN 3
         END ASC