【问题标题】:ORDER BY with Case-Statement DESCORDER BY with Case-Statement DESC
【发布时间】:2011-07-07 08:06:26
【问题描述】:
  • 如何使用CASE 声明ORDER BY
    • 第一组:日期列Col1中的空值按日期列Col2 DESC排序
    • 第二组:日期列中的非空值-Col1Col1 DESC 排序

我尝试了以下方法:

SELECT columns FROM tables WHERE condition
ORDER BY 
    case when Table1.Col1 IS NULL     then 0 end, Table2.Col2 DESC,
    case when Table1.Col1 IS NOT NULL then 1 end, Table1.Col1 DESC

但是排序顺序错误,NOT NULL 值在前(按 Col2 而不是 Col1 排序)。我想我错过了一个细节。

【问题讨论】:

    标签: sql-server-2005 tsql sql-order-by


    【解决方案1】:
    SELECT columns FROM tables 
    WHERE condition 
    ORDER BY      
       case when Table1.Col1 IS NULL then 0 else 1 end ASC      
       ,case when Table1.Col1 IS NULL then Table2.Col2 else Table1.Col1 end DESC
    

    【讨论】:

    • if(Cond,TrueVal,FalseVal) 在此处比使用 case when Cond then TrueVal else FalseVal end 更具可读性
    【解决方案2】:

    这应该可行 - 只需根据第一列是否为空来将第一列设为 0 或 1:

    SELECT columns FROM tables WHERE condition
    ORDER BY 
        case 
            when Table1.Col1 IS NULL     then 0 
                                         else 1
        end,
        case
            when Table1.Col1 IS NULL     then Table1.Col2
                                         else Table1.Col1
        end
    

    【讨论】:

    • 谢谢,现在空值在前面,但非空值不是按Col1 desc 而是Col2 desc 排序的。
    • 刚刚修复 - 抱歉,乍一看我误解了要求
    猜你喜欢
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多