ORDER BY DATE showing NULLS first then most recent dates

前端 未结 8 1232
无人共我
无人共我 2020-11-29 07:21

I have a stored procedure which executes a select statement. I would like my results ordered by a date field and display all records with NULL dates first and then the most

相关标签:
8条回答
  • 2020-11-29 07:27
    OrderBy="ColumnName = NULL desc, ColumnName desc"
    
    0 讨论(0)
  • 2020-11-29 07:30

    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
    
    0 讨论(0)
  • 2020-11-29 07:34

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

    ORDER BY [Submission Date] IS NULL DESC, [Submission Date] ASC
    
    0 讨论(0)
  • 2020-11-29 07:34

    try

    SELECT a,b,c,[Submission Date]
    FROM someView
    ORDER BY isnull([Submission Date],cast('2079/01/01' as datetime)) ASC
    
    0 讨论(0)
  • 2020-11-29 07:45

    @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.

    0 讨论(0)
  • 2020-11-29 07:49

    try this

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

    0 讨论(0)
提交回复
热议问题