具有特定Order By格式的SQL Query

时间:2013-07-09 08:45:08

标签: sql sql-server database

我有一个包含以下值的表

    OperationCode   OperationDesc   OperationOrder
    Repl        Remove          1
    R&I         Remove          1
    Ovrh        Remove          1
    Refn        Prep            1
    Repl        Replace         2
    R&I         Install         2
    Ovrh        Install         2
    Refn        Paint           2

我想编写一个查询来获得以下结果顺序。参见OperationOrder Column

    OperationCode   OperationDesc   OperationOrder
    Repl            Remove      1
    Repl            Replace     2
    R&I             Remove      1
    R&I             Install     2
    Ovrh            Remove      1
    Ovrh            Install     2
    Refn            Prep        1
    Refn            Paint       2

我正在使用sql server 2005.

4 个答案:

答案 0 :(得分:5)

<强> Here is SQLFiddel Demo

以下是您可以尝试的样本查询

SELECT * FROM temp
ORDER BY 
CASE OperationCode 
     WHEN 'Repl' THEN 1
     WHEN 'R&I' THEN 2
     WHEN 'Ovrh' THEN 3
     WHEN 'Refn' THEN 4
END, OperationOrder

答案 1 :(得分:2)

您似乎想要使用ORDER BY

SELECT OperationId, OperationCode, OperationDesc, OperationOrder
FROM YourTable
ORDER By OperationCode ASC

答案 2 :(得分:0)

我想你想要

SELECT 
    ROW_NUMBER() OVER (ORDER BY OperationCode, OperationOrder) as OperationId, 
    OperationCode, 
    OperationDesc, 
    OperationOrder 
FROM SomeTable 
ORDER BY OperationCode, OperationOrder

因为看起来您的OperationId已在每个结果集中更改了顺序,因此必须是自动生成的数字

答案 3 :(得分:0)

如果您需要“OperationCode”的固定订单a.k.a:
Repl&lt; R&amp; I&lt; Ovrh&lt; Refn

SELECT *  
FROM YourTable  
ORDER By   
    OperationCode = 'Repl' DESC,  
    OperationCode = 'R&I'  DESC,  
    OperationCode = 'Ovrh' DESC,  
    OperationCode = 'Refn' DESC

“OperationCode ='Repl'”将返回0/1,如果您使用DESC进行订购,这将放入, 'Repl'值首先结束其他所有内容。