- Trending Categories
- 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
Display the sum of positive and negative values from a column in separate columns with MySQL
For this, you can use CASE statement. Let us first create a table −
mysql> create table DemoTable( Id int, Value int ); Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10,100); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(10,-110); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(10,200); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(10,-678); Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+-------+ | Id | Value | +------+-------+ | 10 | 100 | | 10 | -110 | | 10 | 200 | | 10 | -678 | +------+-------+ 4 rows in set (0.00 sec)
Following is the query to display the sum of positive and negative values from a column in separate columns −
mysql> select Id, sum(case when Value>0 then Value else 0 end) as Positive_Value, sum(case when Value<0 then Value else 0 end) as Negative_Value from DemoTable group by Id;
This will produce the following output −
+------+----------------+----------------+ | Id | Positive_Value | Negative_Value | +------+----------------+----------------+ | 10 | 300 | -788 | +------+----------------+----------------+ 1 row in set (0.00 sec)
Advertisements