简体   繁体   English

MySQL不同行的总和

[英]MySQL sum of distinct rows

I have a query performing INNER JOINs pulling in a relational cross reference table. 我有一个查询,该查询执行INNER JOINs拉入关系交叉引用表。 So based on the query, I'm getting all (one to many) 'fruits' related to a basket. 因此,基于查询,我得到了与篮子相关的所有(一对多)“水果”。 I need to sum the amount of fruits distinctly. 我需要明确总结水果的数量。

| Banana | 1 |
| Banana | 1 |
| Apple  | 1 |
| Pear   | 1 |
| Pear   | 1 |
| Pear   | 1 |

I want the result set to look like this... 我希望结果集看起来像这样...

| Banana | 2 | 
| Apple  | 1 |
| Pear   | 3 |

I tried to SUM() fruit in the SELECT with a GROUP BY but the results were not correct (way off). 我尝试使用GROUP BY在SELECT中求和(SUM()),但是结果不正确(偏离)。 I'm thinking HAVING might need to come into play... anyway, frustrated since this should be pretty easy. 我认为HAVING可能需要发挥作用...无论如何,感到沮丧,因为这应该很容易。

If there are only 1's in the second column, try: 如果第二列中只有1,请尝试:

SELECT fruit, count(fruit)
FROM fruits_table
GROUP BY fruit

Not too difficult with a SUM() and GROUP BY: 使用SUM()和GROUP BY不太困难:

select a.fruit, sum(a.num) as number
from fruits a
group by a.fruit;

SQLFiddle: http://sqlfiddle.com/#!2/3b53a/1 SQLFiddle: http ://sqlfiddle.com/#!2/3b53a/1

Try this code: 试试这个代码:

select fruit_name, sum(qte) 
from fruit_table_name
group by fruit_name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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