How to implement GROUP by range in MySQL?

MySQLMySQLi Database

To group by range in MySQL, let us first create a table. The query to create a table is as follows

mysql> create table GroupByRangeDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > YourRangeValue int
   - > );
Query OK, 0 rows affected (0.78 sec)

Now you can insert some records in the table using insert command.

The query is as follows

mysql> insert into GroupByRangeDemo(YourRangeValue) values(1);
Query OK, 1 row affected (0.14 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(7);
Query OK, 1 row affected (0.15 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(9);
Query OK, 1 row affected (0.14 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(23);
Query OK, 1 row affected (0.13 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(33);
Query OK, 1 row affected (0.15 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(35);
Query OK, 1 row affected (0.16 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(1017);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from GroupByRangeDemo;

The following is the output

+----+----------------+
| Id | YourRangeValue |
+----+----------------+
|  1 |              1 |
|  2 |              7 |
|  3 |              9 |
|  4 |             23 |
|  5 |             33 |
|  6 |             35 |
|  7 |           1017 |
+----+----------------+
7 rows in set (0.04 sec)

Here is the query to group by range

mysql> select round(YourRangeValue / 10), count(YourRangeValue) from GroupByRangeDemo where YourRangeValue < 40 group by round(YourRangeValue / 10)
   - > union
   - > select '40+', count(YourRangeValue) from GroupByRangeDemo where YourRangeValue >= 40;

The following is the output

+----------------------------+-----------------------+
| round(YourRangeValue / 10) | count(YourRangeValue) |
+----------------------------+-----------------------+
| 0                          |                     1 |
| 1                          |                     2 |
| 2                          |                     1 |
| 3                          |                     1 |
| 4                          |                     1 |
| 40+                        |                     1 |
+----------------------------+-----------------------+
6 rows in set (0.08 sec)
raja
Updated on 30-Jul-2019 22:30:25

Advertisements