gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:57:32 25 4
gpt4 key购买 nike

在 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;

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

最佳答案

您需要使用 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>

试一试!!!

关于MySQL 动态显示来自具有出现次数的列的不同值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25631479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com