Counting Groups Returned from GROUP BY in MySQL

Q

How To Count Groups Returned with the GROUP BY Clause in MySQL?

✍: 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:

mysql> SELECT tag AS Category, YEAR(created) AS Year, 
   COUNT(*) AS Counts FROM fyi_links GROUP BY tag, 
   YEAR(created);
+----------+------+--------+
| Category | Year | Counts |
+----------+------+--------+
| DBA      | 2005 |      1 |
| DBA      | 2006 |      2 |
| DEV      | 2004 |      1 |
| DEV      | 2006 |      1 |
| SQA      | 2003 |      1 |
| SQA      | 2006 |      1 |
+----------+------+--------+
6 rows in set (0.00 sec)

mysql> SELECT COUNT(*) FROM (
   SELECT tag AS Category, YEAR(created) AS Year, 
   COUNT(*) AS Counts FROM fyi_links GROUP BY tag, 
   YEAR(created) ) groups;
+----------+
| COUNT(*) |
+----------+
|        6 |
+----------+
1 row in set (0.00 sec)

 

SELECT Statements with JOIN and Subqueries in MySQL

⇒⇒MySQL Database Tutorials

2016-10-17, 174👍, 0💬