Compare values of two columns then select the larger value

前端 未结 6 1275
挽巷
挽巷 2021-02-12 11:03

I need to query a table and select 3 of the values of 4 columns. I need to compare the values of the 3rd column and the fourth column and select the larger value.

For ex

6条回答
  •  情话喂你
    2021-02-12 11:38

    Just so we don't return null:

    SELECT  IIF( a > b, a, COALESCE( a, b )) -- coalesce or isnull
    FROM wherever
    

    Here's a query to test it:

    with whatever as (
      select null as a, 1 as b
      UNION
      select 1 as a, null as b
      union
      select 1 as a, 0 as b
      union
      select 0 as a, 1 as b
      union
      select null as a, null as b
    )
    select( iif( a > b, a, isnull( b, a )))
    from whatever
    

    Should return

    null
    1
    1
    1
    1
    

提交回复
热议问题