3

好的,我之前问过类似的东西,但我已经研究过了,并没有专门找到这个。我有一张表,我需要按字段 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 

任何帮助都会很棒!

4

3 回答 3

2

尝试,

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
于 2012-11-02T13:19:50.130 回答
1

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

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
于 2012-11-02T13:45:22.410 回答
-1

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

于 2012-11-02T20:42:15.903 回答