简体   繁体   中英

How to get the minimum date of several columns, excluding nulls?

insert into table (col1, col2, col3, col4) values ('2015-01-01','2014-01-01', NULL, '2013-01-01')

I am looking for a function like this:

select least_but_no_nulls(col1, col2, col3, col4) from table

result: '2013-01-01'

How can I get the minimum date of several columns, excluding nulls?

Alas, least() now returns NULL if any arguments are NULL . You can use a giant coalesce:

select least(coalesce(col1, col2, col3, col3),
             coalesce(col2, col3, col4, col1),
             coalesce(col3, col4, col1, col2),
             coalesce(col4, col1, col2, col3)
            )

Or, you can use some unlikely value in the future and nullif() :

select nullif(least(coalesce(col1, '9999-01-01'),
                    coalesce(col2, '9999-01-01'),
                    coalesce(col3, '9999-01-01'),
                    coalesce(col4, '9999-01-01'),
                   ), '9999-01-01'
             )

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