Display the sum of positive and negative values from a column in separate columns with MySQL

MySQLMySQLi Database

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)
raja
Published on 03-Sep-2019 13:46:24
Advertisements