简体   繁体   中英

MySQL dynamically display distinct values from a column with count of occurrences?

Using MySQL 5.5.34 on MAMP.

How do I display distinct values with count of occurrences ?

my_table looks like this:

id fruit
01 apple
02 orange
03 grape
04 apple
05 banana
06 orange

What i'm trying to display is something like:

apple 2
banana 1
grape 1
orange 2
fruits 6

I could hard code the values and use count with distinct but I'm sure there is a dynamic way. I've found some examples on here using group by and with rollup , but I can't seem to get the syntax right or find a example.

The non-dynamic way I'm doing right now:

SELECT fruit,COUNT(*) as count
FROM my_table
GROUP BY fruit
ORDER BY fruit ASC
WITH ROLLUP;

I hope somebody has some a clear example. I've been trying for many hours now. thanks!

You need to make the rollup row say fruits instead of NULL using the IFNULL() function

You also don't need ORDER BY

PROPOSED QUERY

SELECT IFNULL(fruit,'fruits') fruit,COUNT(*) as count
FROM my_table
GROUP BY fruit
WITH ROLLUP;

SAMPLE DATA

mysql> drop database if exists fruitdb;
Query OK, 0 rows affected (0.00 sec)

mysql> create database fruitdb;
Query OK, 1 row affected (0.00 sec)

mysql> use fruitdb
Database changed
mysql> create table my_table
    -> (id int not null auto_increment,
    -> fruit varchar(20) not null,
    -> primary key (id));
Query OK, 0 rows affected (0.02 sec)

mysql> insert into my_table (fruit) values
    -> ('apple'),('orange'),('grape'),
    -> ('apple'),('banana'),('orange');
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> select * from my_table;
+----+--------+
| id | fruit  |
+----+--------+
|  1 | apple  |
|  2 | orange |
|  3 | grape  |
|  4 | apple  |
|  5 | banana |
|  6 | orange |
+----+--------+
6 rows in set (0.00 sec)

mysql>

PROPOSED QUERY EXECUTED

mysql> SELECT IFNULL(fruit,'fruits') fruit,COUNT(*) as count
    -> FROM my_table
    -> GROUP BY fruit
    -> WITH ROLLUP;
+--------+-------+
| fruit  | count |
+--------+-------+
| apple  |     2 |
| banana |     1 |
| grape  |     1 |
| orange |     2 |
| fruits |     6 |
+--------+-------+
5 rows in set, 1 warning (0.00 sec)

mysql>

GIVE IT A TRY !!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM