我有一个如下表,我想计算两列(fruit1 和 fruit2)中的不同值
+------+--------+--------+--------+------+
| s_id | s_name | fruit1 | fruit2 | rs |
+------+--------+--------+--------+------+
| 1 | ram | apple | mango | 20 |
| 2 | raj | apple | banana | 13 |
| 3 | aman | orange | banana | 7 |
| 4 | mangal | orange | apple | 16 |
| 5 | ravi | apple | banana | 17 |
| 6 | pawan | apple | apple | 9 |
| 7 | shyam | apple | orange | 11 |
+------+--------+--------+--------+------+
我可以使用以下命令为一列执行此操作,但不能为两列成功,不知道如何实现。
select fruit1, count(*) as count from s_info group by fruit1;
结果是
+--------+-------+
| fruit1 | count |
+--------+-------+
| apple | 5 |
| orange | 2 |
+--------+-------+
但下面是我的预期结果,我没有得到。
+--------+-------+
| fruits | count |
+--------+-------+
| apple | 7 |
| orange | 3 |
| banana | 3 |
| mango | 1 |
+--------+-------+
最佳答案
在进行最终聚合之前使用union all
:
select fruit, count(*)
from ((select fruit1 as fruit from s_info) union all
(select fruit2 as fruit from s_info)
) i
group by fruit;
关于mysql - 如何从两列中获取不同值的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43139807/