我有以下名为Order
的表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)
但我相信我错过了一些东西。
你能帮忙吗?
答案 0 :(得分:7)
如果我正确理解您的问题,您希望返回具有最大购买金额(总)的UserID
。因此,上述记录将产生:
UserID Total Amount
2 12
最简单的解决方案是:
SELECT UserID, SUM(AMOUNT) as TotalAmount
FROM Orders
GROUP BY UserID
ORDER BY TotalAmount DESC
LIMIT 1
如果我错了,我准备编辑这个。 :-)
( PS:请添加您想要的结果)
感谢。
更新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
答案 1 :(得分:4)
见下文,其工作情况。
SELECT userId, sum(Amount) as 'Total'
FROM Orders
GROUP BY userId
ORDER BY Total DESC
LIMIT 1
输出
+++++++++++++++
userId + Total
+++++++++++++++
2 + 12
+++++++++++++++
我在添加新行后尝试了
insert into Orders values (9,1,0,'2010-12-10 12:12:12',10)
输出
+++++++++++++++
userId + Total
+++++++++++++++
1 + 21
+++++++++++++++
答案 2 :(得分:2)
我更喜欢这个解决方案
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将显示两者。