Reputation: 3798
I have a table like below and I want to count distinct values from two columns (fruit1 and 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 |
+------+--------+--------+--------+------+
I am able to do this for one column using below command, but not success for two column, not getting how to achieve this.
select fruit1, count(*) as count from s_info group by fruit1;
which results in
+--------+-------+
| fruit1 | count |
+--------+-------+
| apple | 5 |
| orange | 2 |
+--------+-------+
But below is my expected result, which I am not getting.
+--------+-------+
| fruits | count |
+--------+-------+
| apple | 7 |
| orange | 3 |
| banana | 3 |
| mango | 1 |
+--------+-------+
Upvotes: 3
Views: 94
Reputation: 1269663
Use union all
before doing the final aggregation:
select fruit, count(*)
from ((select fruit1 as fruit from s_info) union all
(select fruit2 as fruit from s_info)
) i
group by fruit;
Upvotes: 4