How to GROUP BY in a select query on positive or negative values?


Following is the syntax to GROUP BY in a select query on positive or negative values:

select *from yourTableName group by -yourColumnName;

Let us first create a table:

mysql> create table DemoTable (Value int);
Query OK, 0 rows affected (0.60 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable values(-10);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(-20);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(-10);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(-10);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(-20);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(-30);
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.12 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output

+-------+
| Value |
+-------+
|   -10 |
|   -20 |
|    20 |
|    10 |
|   -10 |
|   -10 |
|   -20 |
|   -30 |
|    30 |
+-------+
9 rows in set (0.00 sec)

Following is the query to group by positive and negative values:

mysql> select *from DemoTable group by -Value;

This will produce the following output

+-------+
| Value |
+-------+
|   -10 |
|   -20 |
|    20 |
|    10 |
|   -30 |
|    30 |
+-------+
6 rows in set (0.00 sec)

Updated on: 30-Jul-2019

383 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements