按特定顺序排序列

时间:2017-12-12 16:25:08

标签: sql sql-server

我有一个选择声明:

 SELECT DISTINCT LOCATIONTYPE 
 FROM DLOCATION 
 WHERE BinCheckedOut = 'N' 
   AND submitted = 'Y' 
   AND BINNUM > 0 
   AND DISPOSED = 'N';

获取显示列表的所有LOCATIONTYPE。所有可能的LOCATIONTYPE都是:

LOCATIONTYPE
----------------------------------------------
Forage (Represents bin 0 - 999)
International (Represents bin 1000 - 1999)
LongTermRetains (Represents bin 2000 - 2999)
Monitoring (Represents bin 3000 - 3999)
Projects (Represents bin 4000 - 4999)
RawMaterial (Represents bin 5000 - 5999)

但是,我希望它们按箱号以不同的顺序列出。是否可以使用order by binnum执行此操作而不选择binnum?是否有更好的方法来操纵order by按特定顺序列出它们,如下所示?

RawMaterial
Forage  
International
LongTermRetains
Monitoring
Projects

2 个答案:

答案 0 :(得分:1)

您可以使用CASE语句执行自定义有序列表:

SELECT DISTINCT LOCATIONTYPE FROM DLOCATION WHERE BinCheckedOut = 'N' AND
submitted = 'Y' and BINNUM > 0 and DISPOSED = 'N'
ORDER BY 
    CASE 
        WHEN LOCATIONTYPE = 'rawmaterial' THEN 0 
        WHEN LOCATIONTYPE = 'Forage' THEN 1 
        WHEN LOCATIONTYPE = 'International' THEN 2 
        WHEN LOCATIONTYPE = 'LongTermRetains' THEN 3 
        WHEN LOCATIONTYPE = 'Monitoring' THEN 4 
        WHEN LOCATIONTYPE = 'Projects' THEN 5 
    END ASC

答案 1 :(得分:1)

我建议使用GROUP BY和更简单的ORDER BY

SELECT LOCATIONTYPE
FROM DLOCATION
WHERE BinCheckedOut = 'N' and submitted = 'Y' and
      BINNUM > 0 and DISPOSED = 'N'
GROUP BY LOCATIONTYPE
ORDER BY MIN(BINNUM);