MySQL动态地显示具有出现次数的列的不同值?

时间:2014-09-02 20:04:53

标签: mysql group-by

在MAMP上使用MySQL 5.5.34。

如何显示具有出现次数的不同值?

my_table看起来像这样:

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

我试图展示的是:

apple 2
banana 1
grape 1
orange 2
fruits 6

我可以硬编码值并使用不同的计数,但我确信有一种动态方式。我在这里使用group bywith rollup找到了一些示例,但我似乎无法正确使用语法或找到示例。

我现在正在做的非动态方式:

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

我希望有人有一个明确的例子。我现在已经尝试了好几个小时了。谢谢!

1 个答案:

答案 0 :(得分:0)

您需要使用IFNULL()函数将汇总行说成fruits而不是NULL

您也不需要ORDER BY

建议查询

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

样本数据

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>

已建议的查询

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>

给它一个尝试!!!