在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 by
和with rollup
找到了一些示例,但我似乎无法正确使用语法或找到示例。
我现在正在做的非动态方式:
SELECT fruit,COUNT(*) as count
FROM my_table
GROUP BY fruit
ORDER BY fruit ASC
WITH ROLLUP;
我希望有人有一个明确的例子。我现在已经尝试了好几个小时了。谢谢!
答案 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>