
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select Values with Multiple Occurrences and Display Their Count in MySQL
For this, use GROUP BY HAVING clause. Let us first create a table −
mysql> create table DemoTable673( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value int ); Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable673(Value) values(10); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable673(Value) values(20); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable673(Value) values(10); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable673(Value) values(30); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable673(Value) values(20); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable673(Value) values(10); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable673(Value) values(10); Query OK, 1 row affected (0.28 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable673;
This will produce the following output −
+----+-------+ | Id | Value | +----+-------+ | 1 | 10 | | 2 | 20 | | 3 | 10 | | 4 | 30 | | 5 | 20 | | 6 | 10 | | 7 | 10 | +----+-------+ 7 rows in set (0.00 sec)
Following is the query to display only the values having multiple occurrences −
mysql> select Id,count(*) as myValue from DemoTable673 group by Value having count(*) > 1;
This will produce the following output −
+----+---------+ | Id | myValue | +----+---------+ | 1 | 4 | | 2 | 2 | +----+---------+ 2 rows in set (0.00 sec)
Advertisements