ORDER BY DATE showing NULLS first then most recent dates

自古美人都是妖i 提交于 2019-11-27 01:39:16

@Chris, you almost have it.

ORDER BY (CASE WHEN [Submission Date] IS NULL THEN 1 ELSE 0 END) DESC, 
         [Submission Date] DESC

[Edit: #Eppz asked me to tweak the code above as currently shown]

I personally prefer this a lot better than creating "magic numbers". Magic numbers are almost always a problem waiting to happen.

You can do something like this put the NULL's at the bottom:

ORDER BY [Submission Date] IS NULL DESC, [Submission Date] ASC

Standard SQL (ISO/IEC 9075-2:2003 or later - 2008) provides for:

ORDER BY SomeColumn NULLS FIRST

Most DBMS do not actually support this yet, AFAIK.

try

SELECT a,b,c,[Submission Date]
FROM someView
ORDER BY isnull([Submission Date],cast('2079/01/01' as datetime)) ASC
OrderBy="ColumnName = NULL desc, ColumnName desc"

try this

SELECT a,b,c,[Submission Date] FROM someView ORDER BY isnull([Submission Date] ,cast('1770/01/01' as datetime)) ASC

nconantj

I know this is old, but when I found it I noticed the accepted solution, https://stackoverflow.com/a/821856/7177892, could be simplified by making the result of the CASE statement be either today (GETDATE()) or the actual date.

Original:

ORDER BY (CASE WHEN [Submission Date] IS NULL THEN 1 ELSE 0 END) DESC, 
         [Submission Date] DESC

Simplified:

ORDER BY (CASE WHEN [Submission Date] IS NULL 
               THEN GETDATE() 
               ELSE [Submission Date] 
          END) DESC
Marco Leite

I have another suggestion that might be simpler than all the others:

For SQL Server, most of the options don't work, except the case ones.

I found that this actually works great to me: ORDER BY ISNULL(Submission_Date, GETDATE()) DESC

In the order bit of the query, I assign the GETDATE() value to the Submittion_Date values that are null, and the order comes out correctly.

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