- 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
Limit the count using GROUP BY in MySQL
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)
Advertisements