问题描述
我需要找到1996年启动订单最多的customerID。并且我写了以下语句:
SELECT count(orderID) as orderNumber,CustomerID,OrderDate
FROM Orders
where OrderDate between "1996-01-01" AND "1996-12-31"
group
by CustomerID
order
by orderNumber DESC ;
我的问题是我只想打印顶级客户ID,即65,63,20,但我不知道如何编写。 我想我将在此处使用max来过滤已启动6个订单的customerID。 我说的对吗?
解决方法
在MySQL 8.0中,您可以使用rank()
select *
from (
select count(*) as orderNumber,CustomerID,max(OrderDate),rank() over(order by count(*) desc) rn
from Orders
where OrderDate >= '1996-01-01' and OrderDate < '1997-01-01'
group by CustomerID
) t
where rn = 1
注意:
-
select
需要聚合函数,因为它不属于group by
子句 -
如果您的日期有时间成分,半开间隔要比
between
好 -
对文字字符串使用单引号,而不是双引号
OrderDate
子句中的在版本8之前的MySQL版本中,您必须进行两次计数。例如:
class WOFPlayer:
def __init__(self,name,prizeMoney = 0,prizes = []):
self.name = name
self.prizeMoney = prizeMoney
self.prizes = prizes[:]
class WOFComputerPlayer(WOFPlayer):
def __init__(self,difficulty):
WOFPlayer.__init__(self,prizes = [])
self.difficulty = difficulty