ORDER BY with Case-Statement DESC

后端 未结 2 920
無奈伤痛
無奈伤痛 2021-01-12 14:43
  • How to ORDER BY with a CASE-Statement
    • first group: null values in date-column Col1 sorted by date-column Col2 D
相关标签:
2条回答
  • 2021-01-12 15:10
    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
    
    0 讨论(0)
  • 2021-01-12 15:17

    This should work - just make the first column 0 or 1 based on whether it's null or not:

    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
    
    0 讨论(0)
提交回复
热议问题