Finding max of nullable date between two columns in db2

守給你的承諾、 提交于 2020-01-07 03:46:51

问题


I have a table in Db2 called myTable.

It has several columns:

a |  b    | date1        |  date2
---------------------------------------------
1    abc     <null>        2014-09-02
2    aax     2015-12-30    2016-09-02
2    bax     2015-10-20    <null>
2    ayx     2014-12-10    2016-02-12

As seen from values above, date1 and date2 can have null values as well.

How can I get the max of both date1 and date2 together ?

i.e. the output of the query should be 2016-09-02 as that is the max date of all the dates present in date1 and date2.

I am using Db2-9.

Thanks for reading!


回答1:


How about using a UNION query:

SELECT MAX(t.newDate)
FROM
(
    SELECT date1 AS newDate
    FROM myTable
    UNION
    SELECT date2 AS newDate
    FROM myTable
) t

Another option:

SELECT CASE WHEN t.date1 > t.date2 THEN t.date1 ELSE t.date2 END
FROM
(
    SELECT (SELECT MAX(date1) FROM myTable) AS date1,
           (SELECT MAX(date2) FROM myTable) AS date2
    FROM SYSIBM.SYSDUMMY1
) t



回答2:


MAX() is an interesting beast...

It's available as both a scalar function and an aggregate one.

So all you really need is

select max(max(coalesce(date1,'0001-01-01')
              ,coalesce(date2,'0001-01-01') 
              )
          )
from mytable

The outer MAX() is the aggregate version, the inner is the scalar one.



来源:https://stackoverflow.com/questions/39286474/finding-max-of-nullable-date-between-two-columns-in-db2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!