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

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')

我正在寻找这样的函数:

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

结果:“2013-01-01”

如何获得多个列的最小日期,不包括空值?

唉,least() 现在 returns NULL 如果任何参数是 NULL。您可以使用巨型合并:

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

或者,您可以在将来使用一些不太可能的值,并且 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'
             )