Grouping and Filtering by Count
It's possible to aggregate results by counting rows in groups and then filter the results based on the count. You can achieve this using the HAVING clause, which allows you to apply a filter condition on an aggregate function.
Usage:
The following query demonstrates how to use HAVING to filter results by count:
SELECT name, COUNT(*) FROM mytable GROUP BY name HAVING COUNT(*) > 1
In this query, we first group the rows in the 'mytable' by the 'name' column. The COUNT(*) aggregate function counts the number of rows in each group. Subsequently, the HAVING clause filters the results to only include groups with a count greater than 1.
Example:
Consider the following table:
name |
---|
John |
Mary |
John |
Jane |
Jane |
Mark |
The above query will return the following result:
name | COUNT(*) |
---|---|
John | 2 |
Jane | 2 |
As you can see, only the 'John' and 'Jane' groups are returned since they have a count greater than 1.
The above is the detailed content of How Can I Filter Groups Based on Row Count After Grouping Data?. For more information, please follow other related articles on the PHP Chinese website!