从客户表中选择订单数最多的前 3 个客户,并从订单表中获取每个客户的总和

问题描述 投票:0回答:1

客户表 Customer table

订单表 Orders table

我想选择订单数最多的前 3 位客户以及每个客户 ID (custid) 的订单总数

我试过这个

SELECT c.custid, c.name, c.order_count, SUM( o.total ) AS Totalspent 
FROM customer c INNER JOIN orders o ON c.custid = o.custid GROUP BY c.order_count DESC LIMIT 3

它按 order_count 获取数据和分组,但总数是错误的。在根据订单数选择前 3 位客户时,如何从每个客户 (custid) 的订单中获得正确的总数?

mysql select
1个回答
0
投票

您还需要按 custid(以及您想要选择而不聚合的任何其他列)进行分组。然后按 order_count 对结果进行排序,以确保所选的 3 个具有最高的订单数。

SELECT c.custid, c.name, c.order_count, SUM( o.total ) AS Totalspent 
FROM customer c 
INNER JOIN orders o ON c.custid = o.custid 
GROUP BY c.custid, c.name, c.order_count
ORDER BY c.order_count DESC
LIMIT 3

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.