问题
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