简体   繁体   English

如何获取几列的最小日期,不包括空值?

[英]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' 结果:“ 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 . 唉, least()现在返回NULL ,如果任何参数是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() : 或者,您可以在将来使用一些不太可能的值和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'
             )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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