如何从两列中获取不同值的计数?

时间:2017-03-31 11:41:35

标签: mysql sql

我有一个如下表格,我想从两列(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(*)作为来自s_info group by count1的计数;

导致

+--------+-------+
| fruit1 | count |
+--------+-------+
| apple  |     5 |
| orange |     2 |
+--------+-------+

但下面是我的预期结果,我没有得到。

+--------+-------+
| fruits | count |
+--------+-------+
| apple  |     7 |
| orange |     3 |
| banana |     3 |
| mango  |     1 |
+--------+-------+

1 个答案:

答案 0 :(得分:4)

在进行最终聚合之前使用Manufacturer.find(params[:manufacturer_id])

union all