- 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
Count rows having three or more rows with a certain value in a MySQL table
Let us first create a table −
mysql> create table DemoTable -> ( -> UserId int -> ); Query OK, 0 rows affected (0.48 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(30); 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.17 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+----------+ | UserId | +----------+ | 10 | | 20 | | 30 | | 10 | | 10 | | 20 | | 30 | | 10 | | 20 | | 20 | | 40 | +----------+ 11 rows in set (0.00 sec)
Following is the query to count the rows having 3 or more rows with a certain value in a MySQL table −
mysql> select count(*) -> from (select UserId, count(*) as total -> from DemoTable group by UserId -> )tbl -> where total >=3;
This will produce the following output i.e. the values 10 and 20 appears three or more times. Therefore, count is for 2 values −
Output
+----------+ | count(*) | +----------+ | 2 | +----------+ 1 row in set (0.01 sec)
Advertisements