Limit the count using GROUP BY in MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   UserId int,
   UserMessage varchar(100)
);
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1,'Hi');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(2,'Hello');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(2,'Good');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(1,'Nice');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(1,'Awesome');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(1,'Amazing');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(1,'Good Morning');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+--------------+
| UserId | UserMessage  |
+--------+--------------+
|      1 | Hi           |
|      2 | Hello        |
|      2 | Good         |
|      1 | Nice         |
|      1 | Awesome      |
|      1 | Amazing      |
|      1 | Good Morning |
+--------+--------------+
7 rows in set (0.00 sec)

Following is the query to limit the count using GROUP BY −

mysql> select UserId, case when count(*) < 4 then count(*) else 'Greater Than 4' end as 'NumberOfMessage' from DemoTable group by UserId;

This will produce the following output −

+--------+-----------------+
| UserId | NumberOfMessage |
+--------+-----------------+
|      1 | Greater Than 4 |
|      2 | 2              |
+--------+-----------------+
2 rows in set (0.06 sec)
raja
Published on 26-Sep-2019 07:19:21
Advertisements