如何在sql中设置自定义Order

时间:2014-09-02 20:30:22

标签: sql sql-order-by substring customization

我有以下查询:

select distinct CustomerID, SortOrder, Seq
from #result
Order By CASE 
    WHEN Substring(SortOrder, 0, 1) = '~' THEN 9999999 
    else SortOrder 
    END

但是,我收到以下错误消息:如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。

我怎样才能以正确的方式创建此自定义订单?

2 个答案:

答案 0 :(得分:3)

改为使用group by

select CustomerID, SortOrder, Seq
from #result
group by CustomerID, SortOrder, Seq
Order By (CASE WHEN Substring(SortOrder, 0, 1) = '~' THEN 9999999 
               else SortOrder 
          END);

答案 1 :(得分:1)

如果您不介意获取额外的列,那么只需在结果集中包含您的case语句:

SELECT DISTINCT  
    CustomerID,  
    SortOrder,  
    CASE  
    WHEN Substring(SortOrder, 0, 1) = '~' THEN 9999999  
    ELSE SortOrder  
    END 
FROM 
    #result 
ORDER BY  
    CASE  
    WHEN Substring(SortOrder, 0, 1) = '~' THEN 9999999  
    ELSE SortOrder  
    END