"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can SQL Filter Grouped Results Based on Row Count?

Can SQL Filter Grouped Results Based on Row Count?

Posted on 2025-02-06
Browse:931

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

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.

Latest tutorial More>

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