

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to get total occurrences of a value within its own MySQL query?
For this, you can use subquery. Let us first create a table −
mysql> create table DemoTable -> ( -> Value int -> ); Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.36 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
This will produce the following output −
+-------+ | Value | +-------+ | 20 | | 30 | | 20 | | 40 | | 30 | | 20 | +-------+ 6 rows in set (0.00 sec)
Following is the query to get total occurrence of a value −
mysql> select tbl.Value,(SELECT COUNT(*) from DemoTable where Value = tbl.Value) AS Occurrence from DemoTable tbl;
Output
This will produce the following output −
+-------+------------+ | Value | Occurrence | +-------+------------+ | 20 | 3 | | 30 | 2 | | 20 | 3 | | 40 | 1 | | 30 | 2 | | 20 | 3 | +-------+------------+ 6 rows in set (0.00 sec)
- Related Questions & Answers
- How to count the number of occurrences of a specific value in a column with a single MySQL query?
- How can we get the total number of rows affected by MySQL query?
- How to access a JavaScript object using its own prototype?
- How to get the fourth highest value using MySQL query?
- MySQL query to select a random row value (Id and Name) having multiple occurrences (Name)?
- How to count total number of occurrences of an object in a Python list?
- MySQL query to check if a string contains a value (substring) within the same row?
- MySQL query to get a single value from position of comma-separated string?
- Which is the fastest method to get the total row count for a MySQL Query?
- How to get the total number of seconds from a MySQL DATETIME instance?
- MySQL query to find the number of occurrences from two columns?
- How to write Python regular expression to get zero or more occurrences within the pattern?
- MySQL query to sum 3 different values in a column displaying total of each value in result set?
- Sort a MySQL table column value by part of its value?
- How to get the total number of leap days in the years within range in Python?
Advertisements