Home > Database > Mysql Tutorial > How Can I Count Distinct Values and Their Occurrences in MySQL?

How Can I Count Distinct Values and Their Occurrences in MySQL?

DDD
Release: 2025-01-17 22:21:13
Original
706 people have browsed it

How Can I Count Distinct Values and Their Occurrences in MySQL?

Count unique values ​​and their occurrence times in MySQL

Counting unique values ​​and their occurrences is a common task in data processing. In MySQL you can achieve this with a simple query:

<code class="language-sql">SELECT name, COUNT(*) AS count
FROM tablename
GROUP BY name
ORDER BY count DESC;</code>
Copy after login

Instructions:

  • SELECT name, COUNT(*) AS count: Select the name column and use COUNT(*) to count its occurrences (number of occurrences). The results are stored in the count column.
  • FROM tablename: Specify the MySQL table to extract data from. Replace tablename with the actual table name.
  • GROUP BY name: Group results by name column. This ensures that you only count occurrences of unique name values.
  • ORDER BY count DESC: Sort the results in descending order of the count column, displaying the most frequently occurring name value first.

Example:

Consider the following example data:

id name
1 Mark
2 Mike
3 Paul
4 Mike
5 Mike
6 John
7 Mark

Running a query on this data will produce the following results:

name count
Mike 3
Mark 2
Paul 1
John 1

This query concisely and efficiently counts the number of occurrences of each unique name in the table, and sorts the results in descending order by the number of occurrences, allowing users to quickly understand the data distribution.

The above is the detailed content of How Can I Count Distinct Values and Their Occurrences in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template