Home > Database > Mysql Tutorial > Can SQL Filter Grouped Results Based on Row Count?

Can SQL Filter Grouped Results Based on Row Count?

Patricia Arquette
Release: 2024-12-30 16:13:17
Original
945 people have browsed it

Can SQL Filter Grouped Results Based on Row Count?

Filtering by Group Count

In SQL, it is possible to group results and filter based on the number of rows within each group. This can be achieved using the HAVING clause.

Consider the following requirement:

Problem Statement:

Is it possible to group results and then filter by how many rows are in the group? For example:

SELECT * FROM mytable WHERE COUNT(*) > 1 GROUP BY name
Copy after login

Solution:

The HAVING clause allows us to apply a filter on an aggregate function. In this case, we can filter on the COUNT(*) aggregate function to select groups with more than one row. The correct syntax is:

SELECT name, COUNT(*)
FROM mytable
GROUP BY name
HAVING COUNT(*) > 1
Copy after login

This query will return all the unique names and the count of rows associated with each name, where the count is greater than 1.

The above is the detailed content of Can SQL Filter Grouped Results Based on Row Count?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template