简体   繁体   中英

Oracle SQL - Select oldest of 3 dates, but ignore NULLs

I have this Oracle SQL statement to get the oldest of 3 dates:

SELECT LEAST(DATE_1,DATE_2,DATE_3) FROM MYTABLE

However, if one of the dates is NULL, the entire LEAST function will return NULL, regardless of whether the the other dates are not NULL. I would like to get the oldest of the three dates, but ignore any NULL dates, so that the only time LEAST would return NULL is if all three dates are NULL.

I also cannot have the function return incorrect dates, so this will not work:

SELECT LEAST(NVL(DATE_1,SYSDATE),NVL(DATE_2,SYSDATE),NVL(DATE_3,SYSDATE)) FROM MYTABLE

What's the cleanest way to do this?

Here is one way:

SELECT LEAST(COALESCE(DATE_1, DATE_2, DATE_3),
             COALESCE(DATE_2, DATE_1, DATE_3),
             COALESCE(DATE_3, DATE_2, DATE_1)
            )
FROM MYTABLE

How about this?

SELECT LEAST(NVL(DATE_1,TO_DATE('9999-01-01','yyyy-mm-dd')), NVL(DATE_2,TO_DATE('9999-01-01','yyyy-mm-dd')), NVL(DATE_3,TO_DATE('9999-01-01','yyyy-mm-dd'))) FROM MYTABLE

The only downside is that it returns 9999-01-01 instead of NULL if all three are NULL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM