如何形成sql结构以获得最大总值

时间:2014-12-16 19:54:37

标签: mysql

我有一张桌子"销售"

transactionId  salepersonId amount
1                1          100
2                1          200
3                2          50
4                3          60
5                3          200

我想知道如何让总销售额最高的销售人员。 我知道我需要使用max和sum,但我不知道如何将它们组合起来。 这就是我得到的

   select salespersonId, sum(amount) from sales group by salesperson;

这会给我每个人的总销售额,但我不确定下一步要获得最大值。有人能帮助我吗?

3 个答案:

答案 0 :(得分:1)

标准的SQL方法是使用order bylimittop

select salespersonid, sum(amount) as total
from sales
group by salespersonid
order by total desc
limit 1;

在SQL Server中,您将使用top 1而不是limit 1

select top 1 salespersonid, sum(amount) as total
from sales
group by salespersonid
order by total desc;

答案 1 :(得分:0)

select salespersonId, sum(amount) as total 
from sales group by salespersonID ORDER BY total DESC LIMIT 1;

答案 2 :(得分:0)

这应该有效

select salepersonId, sum(amount) from sales group by amount DESC limit 1

select rec.id, max(rec.amt) from (select salepersonId id, sum(amount) amt from sales group by salepersonId) AS rec