MYSQL选择最大购买金额
我有一个名为Order的下表MYSQL选择最大购买金额,mysql,sql,Mysql,Sql,我有一个名为Order的下表 Orders Table ___________________________________________________ orderiD | userId | OrderType | Order_Date | Amount ________|________|___________|____________|________ 1 1 0 12/12/2009 1 2 1
Orders Table
___________________________________________________
orderiD | userId | OrderType | Order_Date | Amount
________|________|___________|____________|________
1 1 0 12/12/2009 1
2 1 1 13/12/2009 2
3 1 1 14/12/2009 3
4 2 0 12/12/2009 4
5 2 1 16/12/2009 2
6 1 0 14/12/2009 5
7 2 1 17/12/2009 4
8 2 0 10/12/2010 2
___________________________________________________
我需要创建一个查询,返回用户id和最大购买金额
我尝试了以下方法
Select MAX(GRP.sumAmmount), o.userId join
(Select SUM(o.Amount) as sum_ammount, o.userId as UID from Orders GROUP BY(o.userID)) as GRP on o.userId=GRP.UID GROUP BY(GRP.UID)
但我相信我错过了什么
您能帮忙吗?如果我正确理解了您的问题,您希望返回购买金额最大的
用户ID
。因此,上述记录将导致:
UserID Total Amount
2 12
最简单的解决方案是:
SELECT UserID, SUM(AMOUNT) as TotalAmount
FROM Orders
GROUP BY UserID
ORDER BY TotalAmount DESC
LIMIT 1
如果我错了,我准备编辑此内容。:-)(注:请添加您想要的结果)
谢谢 更新1 从您的查询中派生:
Select MAX(SUM(o.Amount)) as sum_ammount,
o.userId as UID
FROM Orders o
GROUP BY o.userID
ORDER BY sum_ammount DESC
LIMIT 1
见下文,其工作原理
SELECT userId, sum(Amount) as 'Total'
FROM Orders
GROUP BY userId
ORDER BY Total DESC
LIMIT 1
输出为
+++++++++++++++
userId + Total
+++++++++++++++
2 + 12
+++++++++++++++
+++++++++++++++
userId + Total
+++++++++++++++
1 + 21
+++++++++++++++
我还尝试在添加新行后作为
插入订单值(9,1,0,'2010-12-10 12:12:12',10)
输出为
+++++++++++++++
userId + Total
+++++++++++++++
2 + 12
+++++++++++++++
+++++++++++++++
userId + Total
+++++++++++++++
1 + 21
+++++++++++++++
我更喜欢这个解决方案
SELECT UserID, SUM(AMOUNT) as TotalAmount
FROM Orders
GROUP BY UserID
having SUM(AMOUNT) = (select sum(amount) as col1
from orders
group by userid
order by col1 desc
limit 1
)
此sql将显示具有最大购买量的所有用户
只要尝试将orderid 1的数量更改为2,那么此sql将同时显示两者。我认为您的sql语法无效,因为您是从未知表加入
GRP
。我相信它的id顺序是o
。这和我的答案有什么区别?@johntetwoo:我甚至没有看到你的疑问。。。我刚刚在这里测试并回答了…@johntotetwoo:添加新数据和测试足以告诉你我在我这边测试过。。。明白了吗???我已经改变了我的投票结果,不管怎样,这一点都不重要。很好的一天!你否决了我。。。正确的??别担心,我会投票给你……:)不幸的是,第二个查询不起作用,它产生的结果与选择SUM(o.Amount)作为SUM\u Amount,选择o.userId作为订单中的UID o GROUP BY(o.userId)完全相同。第一个查询是否回答了您的问题?我刚刚更新了第二个查询。这不会处理多个具有相同最大和的用户。遗憾的是,第二个查询对我不起作用,它抛出“错误代码:1111.组函数的使用无效”