[英]How to get count of distinct values from two columns?
我有一個如下表,我想從兩列(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 |
+------+--------+--------+--------+------+
我可以使用下面的命令在一列中執行此操作,但對於兩列則無法成功執行,但無法獲得實現方法。
選擇fruit1,count(*)作為s1的s_info組中的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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.