首页 > 解决方案 > 使用连接查找最大值的 SQL 查询

问题描述

我正在尝试解决这个问题 - 从给定的数据集中,编写一个 SQL 查询来查找在 1996 年下达最多订单的客户的 CustomerID。

这是我写的,但这似乎没有给出正确的答案 -

select c.customerId
     , COUNT(*) 
  from orders o 
  JOIN customers c 
    ON o.customerId = c.customerId 
 WHERE YEAR(o.orderDate  ) = 1996 
 GROUP 
    BY c.customerId

在此处输入图像描述

标签: mysqlsqlinner-join

解决方案


您可以将窗口函数用于group by

select customerid
from (select o.customerId, count(*),
             rank() over (order by count(*) desc) as seqnum
      from orders o
      where o.orderDate >= '1996-01-01' and o.orderDate < '1997-01-01'
      group by o.customerId
    ) c
where seqnum = 1;

推荐阅读