Compare values of two columns then select the larger value

前端 未结 6 1277
挽巷
挽巷 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:36

    I would start by creating a view.

    CREATE VIEW t_c
    SELECT id, c1 AS c FROM t
    UNION
    SELECT id, c2 AS c FROM t;
    

    Then I would select from that view.

    SELECT id, MAX(c) FROM t_c GROUP BY id;
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-12 11:41

    In T-SQL the IF command is for programatic control. For example:

    • IF x THEN doSQLStatement1 ELSE doSQLStatement2


    Within a SQL statement, you need CASE.

    CASE WHEN a > b THEN a ELSE b END
    
    0 讨论(0)
  • 2021-02-12 11:41
    select column1, coloumn2, case when column3 < column4 then column4 else coloum3 end from table. 
    
    0 讨论(0)
  • 2021-02-12 11:45

    Try this code:

    SELECT column1, column2,
           (CASE WHEN column3 > column4 THEN column3 ELSE column4 END)
      FROM Table1
    

    Result:

    COLUMN1   COLUMN2  Hybrid
     hello     hello      5
      hi         hi       7
    

    Here you have complete sample on SQL Fiddle.

    0 讨论(0)
  • 2021-02-12 11:56

    You can use CASE, but if one of the values is 'null', the 'null' is considered the greatest value.

    To solve this problem you can use GREATEST

    SELECT GREATEST(column3, column4)
    FROM Table1
    
    0 讨论(0)
提交回复
热议问题