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 timesbanana
- appears 5 timespear
- appears 3 timesI 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.
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.
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.
Without a GROUP BY clause, a query containing an aggregate function over zero input rows will return a single row as the result.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With