SQL案例顺序按特定顺序

时间:2012-11-02 13:17:46

标签: sql sql-order-by case

好的,之前我问了类似的东西,但我已经研究过了,并没有特别发现。 我有一个表,我需要在字段OptionName(NVarChar)和IsActive(BIT)上排序。

我需要DDL的结果如下:

Option A
Option B
Option C
Options that are Active, by OptionName ASC 
Option D
Options that are Inactive, by OptionName ASC 

到目前为止我已经

ORDER BY CASE WHEN PortalName = 'Company, Inc' THEN 0 ELSE 1 END,
         CASE WHEN PortalName = 'Setup' THEN 1 ELSE 2 END,
         CASE WHEN PortalName = 'Daily Routine' THEN 2 ELSE 3 END,
         CASE WHEN IsActive = 1 THEN 3 ELSE 4 END, 
         CASE WHEN PortalName = 'Master Option' THEN 4 ELSE 5 END,
         PortalName ASC

但是这会将结果返回为:

Option A
Option B
Option C
Option D
Options that are Active, by OptionName ASC 
Options that are Inactive, by OptionName ASC 

任何帮助都会很棒!

3 个答案:

答案 0 :(得分:1)

试,

ORDER BY CASE WHEN PortalName = 'Company, Inc' THEN 0 
              WHEN PortalName = 'Setup' THEN 1 
              WHEN PortalName = 'Daily Routine' THEN 2 
              WHEN IsActive = 1 THEN 3 
              WHEN PortalName = 'Master Option' THEN 4 
         ELSE 5 END,
         PortalName ASC

答案 1 :(得分:1)

将订单的每个部分视为不同的列...将案例应用于每个组件。首先获得第一部分......然后是第二部分。如果它不适用于第二部分,只需使它始终具有相同的值......就像......

ORDER BY 
  CASE WHEN PortalName = 'Company, Inc' THEN 1
       WHEN PortalName = 'Setup' THEN 2
       WHEN PortalName = 'Daily Routine' THEN 3
       WHEN PortalName = 'Master Option' THEN 4 ELSE 5 END,
  CASE WHEN IsActive = 1 THEN 1 ELSE 2 END,
  PortalName ASC

答案 2 :(得分:-1)

得到答案:CASE WHEN PortalName ='Master Option'那么9999 ELSE 5 END