Selecting most recent date between two columns

前端 未结 13 1323
再見小時候
再見小時候 2020-12-30 22:15

If I have a table that (among other columns) has two DATETIME columns, how would I select the most recent date from those two columns.

Example:

相关标签:
13条回答
  • 2020-12-30 23:02

    Why couldn't you use the GREATEST function?

    select id, date1, date2, GREATEST( nvl(date1,date2) , nvl(date2, date1) )
    from table1;
    

    I included a NVL to ensure that NULL was evaluated correctly, otherwise if either Date1 or Date2 is null, the Greatest returns NULL.

    ID  Date1       Date2       MostRecentDate
    1   1/1/2008    2/1/2008    2/1/2008
    2   2/1/2008    1/1/2008    2/1/2008
    3   1/10/2008   1/10/2008   1/10/2008
    4   -null-      2/10/2008   2/10/2008
    5   2/10/2008   -null-      2/10/2008
    
    0 讨论(0)
  • 2020-12-30 23:05
    select max(d) ChangeDate
    from (values(@d), (@d2)) as t(d)
    
    0 讨论(0)
  • 2020-12-30 23:07

    From SQL Server 2012 it's possible to use the shortcut IIF to CASE expression though the latter is SQL Standard:

    SELECT ID,
           IIF(DateColA > DateColB, DateColA, DateColB) AS MostRecentDate
      FROM theTable
    
    0 讨论(0)
  • 2020-12-30 23:09

    All other correct answers as already posted.

    But if you are still really looking for MAX keyword then here is a way :

    select ID , MAX(dt) from 
    (  select Id , Date1 as dt from table1
       union  
       select ID , Date2 from table2
    ) d
    group by d.Id
    
    0 讨论(0)
  • 2020-12-30 23:10

    Other than case statement, I don't believe so...

      Select Case When DateColA > DateColB Then DateColA 
                  Else DateColB End MostRecent
      From Table ... 
    
    0 讨论(0)
  • 2020-12-30 23:13

    Whenever possible, use InLine functions as they suffer none of the performance issues generally associated with UDFs...

    Create FUNCTION MaximumDate 
    (   
    @DateTime1 DateTime,
    @DateTime2 DateTime
    )
    RETURNS TABLE 
    AS
    RETURN 
    (
        Select Case When @DateTime1 > @DateTime2 Then @DateTime1
                    Else @DateTime2 End MaxDate
    )
    GO 
    

    For usage guidelines, see Here

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