Greatest not null column

喜你入骨 提交于 2020-01-22 17:39:06

问题


I need to update a row with a formula based on the largest value of two DATETIME columns. I would normally do this:

GREATEST(date_one, date_two)

However, both columns are allowed to be NULL. I need the greatest date even when the other is NULL (of course, I expect NULL when both are NULL) and GREATEST() returns NULL when one of the columns is NULL.

This seems to work:

GREATEST(COALESCE(date_one, date_two), COALESCE(date_two, date_one))

But I wonder... am I missing a more straightforward method?


回答1:


COALESCE(GREATEST(date_one, date_two), date_one, date_two)




回答2:


My solution for multiple columns is:

SELECT NULLIF(
  GREATEST(
    NVL(NULL,     to_date('01011980','ddmmyyyy')), --COLUMN 1
    NVL(sysdate,  to_date('01011980','ddmmyyyy')), --COLUMN 2
    NVL(NULL,     to_date('01011980','ddmmyyyy')), --COLUMN 3
    NVL(sysdate-1,to_date('01011980','ddmmyyyy'))  --COLUMN 4
  ),to_date('01011980','ddmmyyyy')
) as greatest_date
FROM DUAL;


来源:https://stackoverflow.com/questions/2684090/greatest-not-null-column

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