Selecting most recent date between two columns

前端 未结 13 1369
再見小時候
再見小時候 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')
    

提交回复
热议问题