简体   繁体   中英

How to get count of distinct values from two columns?

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 |
+--------+-------+

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM