gpt4 book ai didi

MySQL GROUP BY 和 COUNT 多列

转载 作者:可可西里 更新时间:2023-11-01 07:30:27 24 4
gpt4 key购买 nike

我有一个 MySQL 表如下:

+----+-------+-------+-------+-------+-------+
| ID | MON | TUE | WED | THU | FRI |
+----+-------+-------+-------+-------+-------+
| 0 | Bike | Bike | Walk | Bike | Car |
| 1 | Car | Car | Car | Bus | Car |
| 2 | Bus | Train | Bus | Bus | Train |
| 3 | Car | Car | Car | Walk | Car |
+----+-------+-------+-------+-------+-------+

我将如何分组并计算所有天数,以获得一周内每种交通工具的总模式。例如:

+--------+-------+
| MODE | COUNT |
+--------+-------+
| Bike | 3 |
| Bus | 4 |
| Car | 9 |
| Train | 2 |
| Walk | 2 |
+--------+-------+

我试过使用:

SELECT COUNT(*), Mon 
FROM transport
GROUP BY Mon, Tue, Wed, Thu, Fri

但这会为每天的每个唯一值创建一个新组。

最佳答案

一种方法是生成一个子查询,使用 union all 运算符在一列中选择传输模式,然后计算出现次数:

SELECT   mode, COUNT(*)
FROM (SELECT mon AS mode FROM transport UNION ALL
SELECT tue AS mode FROM transport UNION ALL
SELECT wed AS mode FROM transport UNION ALL
SELECT thu AS mode FROM transport UNION ALL
SELECT fri AS mode FROM transport) t
GROUP BY mode

关于MySQL GROUP BY 和 COUNT 多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31218825/

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