ORDER BY with Case-Statement DESC

心已入冬 提交于 2019-12-01 02:53:00

问题


  • How to ORDER BY with a CASE-Statement
    • first group: null values in date-column Col1 sorted by date-column Col2 DESC
    • second group: not-null values in date-column-Col1 sorted by Col1 DESC

I've tried following:

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

But the sort order is wrong, the NOT NULL values are first(sorted by Col2 instead of Col1). I think i've missed a detail.


回答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



回答2:


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


来源:https://stackoverflow.com/questions/6607575/order-by-with-case-statement-desc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!