Use the CASE statements and set conditions for the same. Let us first create a table −
mysql> create table DemoTable -> ( -> X int, -> Y int -> ); Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(20,30); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(40,15); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(80,85); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
This will produce the following output −
+------+------+ | X | Y | +------+------+ | 20 | 30 | | 40 | 15 | | 80 | 85 | +------+------+ 3 rows in set (0.00 sec)
Following is the query to select the sum of the column values with higher value in each row.
mysql> SELECT SUM(CASE WHEN X > Y THEN X ELSE Y END) from DemoTable;
Output
This will produce the following output −
+----------------------------------------+ | SUM(CASE WHEN X > Y THEN X ELSE Y END) | +----------------------------------------+ | 155 | +----------------------------------------+ 1 row in set (0.00 sec)