How To Count Groups Returned with the GROUP BY Clause

Q

How To Count Groups Returned with the GROUP BY Clause? - Oracle DBA FAQ - Understanding SQL SELECT Query Statements

✍: FYIcenter.com

A

If you use the COUNT(*) function on groups returned with the GROUP BY clause, it will count the number of rows within each group, not the number of groups. If you want to count the number of groups, you can put the GROUP BY query into a subquery and apply the COUNT(*) function on the main query as shown in the following tutorial exercise:

SQL> SELECT first_name, COUNT(*) FROM employees 
  GROUP BY first_name HAVING COUNT(*) > 1;
FIRST_NAME             COUNT(*)
-------------------- ----------
Peter                         3
Michael                       2
Steven                        2
John                          3
Julia                         2
William                       2
Karen                         2
Kevin                         2
......

SQL> SELECT COUNT(*) FROM (
    SELECT first_name, COUNT(*) FROM employees 
    GROUP BY first_name HAVING COUNT(*) > 1
  );
  COUNT(*)
----------
        13

2007-04-19, 5020👍, 0💬