How to find least non-null column in one particular row in SQL?

后端 未结 8 1020
别跟我提以往
别跟我提以往 2020-12-29 07:36

I am trying to find the lowest number in two columns of a row in the same table, with the caveat that one of the columns may be null in a particular row. If one of the colum

8条回答
  •  渐次进展
    2020-12-29 08:06

    This may perform a bit better (may have to be converted to corresponding MySql syntax):

    SELECT
      CASE
        WHEN Col1 IS NULL THEN Col2
        WHEN Col2 IS NULL THEN Col1
        ELSE Least(Col1, Col2)
      END
    

    Another alternative (probably slower though, but worth a try):

    SELECT Col1
    WHERE Col2 IS NULL
    UNION
    SELECT Col2
    WHERE Col1 IS NULL
    UNION
    SELECT least(Col1, Col2)
    WHERE Col1 IS NOT NULL AND Col2 IS NOT NULL
    

提交回复
热议问题