2015-11-10 30 views
0
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”

我怎样才能得到几列的最小日期,不包括空?

回答

1

唉,least()现在返回NULL如果有任何参数是NULL。您可以使用一个巨大的COALESCE:

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' 
      ) 
相关问题