Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY the number of rows returned by GROUP BY in MySQL

Tags:

mysql

group-by

I have a table - for the purposes of this question, it has one column word. The following information is in this table:

  • apple - appears 3 times
  • banana - appears 5 times
  • pear - appears 3 times

I wrote the following SQL code to select each word uniquely, along with the number of times that word appears in the table:

SELECT word, COUNT(word) FROM table GROUP BY word ORDER BY COUNT(word) DESC;

This returns me the following information:

--------------------------
| word     | COUNT(word) |
--------------------------
| banana   | 5           |
--------------------------
| apple    | 3           |
--------------------------
| pear     | 3           |
--------------------------

Is there a way to write a query to return the following information:

-----------------------------
| COUNT(word) | words       |
-----------------------------
| 5           | banana      |
-----------------------------
| 3           | apple, pear |
-----------------------------

I was thinking along the lines of double GROUP BY, but haven't thought of much yet.

like image 948
Lucas Avatar asked Jan 11 '16 00:01

Lucas


People also ask

How do I COUNT the number of rows returned by a query in MySQL?

Counting all of the Rows in a Table. To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.

How do I COUNT the number of rows in a GROUP BY?

To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.

How many rows are returned when no GROUP BY is part of an aggregate query?

Without a GROUP BY clause, a query containing an aggregate function over zero input rows will return a single row as the result.

How do I COUNT the number of rows returned?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.


1 Answers

You can use GROUP_CONCAT:

SELECT word_count, GROUP_CONCAT(word SEPARATOR ', ') as words
FROM (SELECT word, COUNT(word) as word_count
      FROM table 
      GROUP BY word) w
GROUP BY word_count
ORDER BY word_count DESC;
like image 134
wogsland Avatar answered Sep 25 '22 14:09

wogsland