【问题标题】:How to get count of distinct values from two columns?如何从两列中获取不同值的计数?
【发布时间】:2017-08-25 16:10:24
【问题描述】:

我有一个如下表,我想计算两列(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 |
+------+--------+--------+--------+------+

我可以使用以下命令为一列执行此操作,但两列未成功,不知道如何实现。

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

【问题讨论】:

    标签: mysql sql


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      相关资源
      最近更新 更多