Select the sum of the column with the highest value in the achievement row

I have this table:

a   b
-----
1   3
4   3
2   1

      

From where I would like to select the sum of whichever value is higher between a and b.

I tried with the following query, but it SUM()

doesn't recognize the value that I want to calculate it.

SELECT IF(a > b, a, b) AS number, SUM(number) FROM table;

      

+3


source to share


2 answers


What about case



SELECT SUM(CASE WHEN a > b THEN a ELSE b END)
FROM table

      

+2


source


You can try like this IF ():

SELECT SUM( IF( a > b, a, b ) ) FROM test

      

or case



SELECT SUM(CASE WHEN a > b THEN a ELSE b END) FROM test

      

Sql Fiddle: http://sqlfiddle.com/#!2/204f7/1

+1


source







All Articles