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
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
This query will return all the unique names and the count of rows associated with each name, where the count is greater than 1.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3