仅获取Group By返回的最高值

时间:2016-06-30 06:59:01

标签: php mysql

这是我的表格(简化)的样子

agentID|amount
   1   |   5  
   2   |   2  
   3   |   4  
   3   |   2  
   1   |   3

现在,如果我这样做

SELECT agentID, SUM(amount) AS totalAmount FROM myTable GROUP BY agentID

我会得到每个agentID的金额总和。但是如果我只对返回的具有最大金额(金额)的agentID感兴趣呢?

尝试了类似

的内容
SELECT agentID, MAX(SUM(amount) AS Bought) FROM myTable GROUP BY agentID

OR

SELECT MAX(SELECT agentID, SUM(amount) AS Bought FROM myTable GROUP BY agentID) FROM myTable

但它返回语法错误:p

1 个答案:

答案 0 :(得分:1)

你可以在最后添加 ORDER BY

SELECT agentID, SUM(amount) AS totalAmount FROM myTable GROUP BY agentID ORDER BY SUM(amount) DESC LIMIT 1;