mysql - 使用连接查找最大值的 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
解决方案
您可以将窗口函数用于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;
推荐阅读
- php - Wordpress子主题functions.php的完整片段
- javascript - 使用角度材料中的 MatTableDataSource 类型“EventTarget”上不存在属性“值”
- angular - 根据服务器是否运行注入不同的服务
- flutter - 带有 Getx 的 Flutter DropdownButton 小部件
- react-native - react native 是否支持 box-shadow 参数传播半径?
- python - 有没有办法像 google colab 一样在 jupyter lab 中快速获得干净的虚拟环境?
- python - 针对虚拟变量和分组值绘图
- r - 在行名中使用 grep 剪切数据框
- angular - Ionic Video 加载资源失败
- php - Laravel 5.5 - 从原始查询更改 SQL 时,它不起作用