在MySQL中,如何找到在特定列上分组的N个最大值的总和? [英] In MySQL, how can I find the sum of the N largest values grouped on a particular column?
本文介绍了在MySQL中,如何找到在特定列上分组的N个最大值的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Possible Duplicate:
mysql: Using LIMIT within GROUP BY to get N results per group?
我有以下数据.
id val
smith 20
smith 10
smith 8
smith 30
jones 40
jones 10
jones 30
jones 30
然后我想要的是按ID分组,然后将每个ID的两个最大值相加.
What I want then is to group by id and sum the two largest values for each id.
smith 50 from 30+20
jones 70 from 40+30
谢谢.
推荐答案
如果您不担心只获取每个ID的前两个值之和,则可以这样做:
If you weren't worried about getting the sum of only the top two values for each ID, you would want this:
SELECT SUM(val) FROM table_name GROUP BY id ORDER BY id ASC
However, the "How do I get the top N values within a group" question is a duplicate, answered here: Using LIMIT within GROUP BY to get N results per group?
这篇关于在MySQL中,如何找到在特定列上分组的N个最大值的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文