MySQL: get MAX or GREATEST of several columns, but with NULL fields

后端 未结 4 2226
刺人心
刺人心 2020-12-07 22:24

I\'m trying to select the max date in three different fields in each record (MySQL) So, in each row, I have date1, date2 and date3: date1 is always filled, date2 and date3 c

4条回答
  •  被撕碎了的回忆
    2020-12-07 22:54

    If date1 can never be NULL, then the result should never be NULL, right? Then you could use this, if you want NULL dates be not counted in the calculations (or change the 1000-01-01 to 9999-12-31, if you want Nulls to count as the "end of time"):

    GREATEST( date1
            , COALESCE(date2, '1000-01-01')
            , COALESCE(date3, '1000-01-01')
            ) AS datemax
    

提交回复
热议问题