- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to select the sum of the column values with higher value in reach row with MySQL?
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)
Advertisements