SQL 查询使用连接查找最大值
SQL Query to find max using joins
我正在尝试解决这个问题 -
根据给定的数据集,编写 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
这应该可行(下面的逻辑使用 windows 函数)-
Select t.customerId
from
(Select Tab.*,
Rank() over(partition by customerId order by number_of_orders desc) as rank_orders
from
(select c.customerId,
, COUNT(distinct order_id) As number_of_orders
from
orders as o
INNER JOIN
customers as c
ON o.customerId = c.customerId
WHERE YEAR(o.orderDate ) = 1996
group by c.customerId) Tab) t
where t.rank_orders = 1;
您可以将 window 函数与 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;
我正在尝试解决这个问题 - 根据给定的数据集,编写 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
这应该可行(下面的逻辑使用 windows 函数)-
Select t.customerId
from
(Select Tab.*,
Rank() over(partition by customerId order by number_of_orders desc) as rank_orders
from
(select c.customerId,
, COUNT(distinct order_id) As number_of_orders
from
orders as o
INNER JOIN
customers as c
ON o.customerId = c.customerId
WHERE YEAR(o.orderDate ) = 1996
group by c.customerId) Tab) t
where t.rank_orders = 1;
您可以将 window 函数与 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;