Get the minimum non zero value across multiple columns

▼魔方 西西 提交于 2019-12-04 21:41:10

Try NULLIF function:

SELECT LEAST(
        nullif( number1, 0 ), 
        nullif( number2, 0 ), 
        nullif( number3, 0 ), 
        nullif( number4, 0 )) 
FROM numbers

Demo --> http://www.sqlfiddle.com/#!12/641fb3/1

LEAST will ignore NULL values, so the following should work:

select least(n1, n2, n3, n4)
from (
   select case when number1 <= 0 then null else number1 end as n1,
          case when number2 <= 0 then null else number2 end as n2,
          ...
    from numbers
) t

This way you can also deal with negative numbers. If you are sure there will never be negative values, kordirko's answer is probably a bit easier.

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