ORDER BY与Case-Statement DESC

Tim*_*ter 6 t-sql sql-server-2005 sql-order-by

  • 如何ORDER BY使用CASE-Statement
    • 第一组:日期列中的空值按日期列Col1排序Col2 DESC
    • 第二组:日期列中的非空值 - Col1排序依据Col1 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
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*ica 7

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
Run Code Online (Sandbox Code Playgroud)