Selecting most recent date between two columns

前端 未结 13 1321
再見小時候
再見小時候 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 22:52

    CASE is IMHO your best option:

    SELECT ID,
           CASE WHEN Date1 > Date2 THEN Date1
                ELSE Date2
           END AS MostRecentDate
    FROM Table
    

    If one of the columns is nullable just need to enclose in COALESCE:

    .. COALESCE(Date1, '1/1/1973') > COALESCE(Date2, '1/1/1973')
    
    0 讨论(0)
  • 2020-12-30 22:55

    I think the accepted answer is the simplest. However, I would watch for null values in the dates...

    SELECT ID,
           CASE WHEN ISNULL(Date1,'01-01-1753') > ISNULL(Date2,'01-01-1753') THEN Date1
                ELSE Date2
           END AS MostRecentDate
    FROM Table
    
    0 讨论(0)
  • 2020-12-30 23:00
    select ID, 
    case
    when Date1 > Date2 then Date1
    else Date2
    end as MostRecentDate
    from MyTable
    
    0 讨论(0)
  • 2020-12-30 23:00
    select ID,(select max(d) from (select Date1 d uninon select Date2 d) as t) as MaxDate
    from MyTable
    
    0 讨论(0)
  • 2020-12-30 23:02

    AFAIK, there is no built-in function to get the maximum of two values, but you can write your own easily as:

    CREATE FUNCTION dbo.GetMaximumDate(@date1 DATETIME, @date2 DATETIME)
    RETURNS DATETIME
    AS
    BEGIN
        IF (@date1 > @date2)
            RETURN @date1
        RETURN @date2
    END
    

    and call it as

    SELECT Id, dbo.GetMaximumDate(Date1, Date2)
    FROM tableName
    
    0 讨论(0)
  • This thread has several solutions. If you had more than 2 dates to compare, "unpivot" might be preferable to writing a series of case statements. The following is blatantly stolen from Niikola:

    select id, max(dDate) MostRecentDate
      from YourTable
        unpivot (dDate for nDate in (Date1, Date2, Date3)) as u
      group by id 
    

    Then you can order by dDate, if that's helpful.

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