我希望按国家/地区分组并找到最大购买量 与那个国家有关。
SELECT
country ,
customer_name,
total_purchased
FROM total
GROUP BY 1,2
ORDER BY 1
输出:
country customer_name total_purchased
Australia Diego Gutiérrez 39.6
Australia Mark Taylor 81.18
Austria Astrid Gruber 69.3
Belgium Daan Peeters 60.3899999
Brazil Alexandre Rocha 69.3
Brazil Eduardo Martins 60.39
我正在寻找一种回报该国最佳客户的方法。最佳客户是指该国花费更多金钱的人。
例如:在澳大利亚,我想要两个人同一个澳大利亚的桌子,以及一个最大购买量的客户。我该怎么做?我试过了,但到目前为止我还想不出办法。
所需的输出:
country customer_name total_purchased
Australia Mark Taylor 81.18
Austria Astrid Gruber 69.3
Belgium Daan Peeters 60.3899999
Brazil Eduardo Martins 60.39
答案 0 :(得分:1)
我不知道您使用的是哪个版本的SQL,但是分析功能可以为您提供帮助,尽管旧的MySQL版本中没有。 如果您可以使用分析功能,则可能会发生以下情况:
SELECT country,
customer_name,
total_purchased
FROM (
SELECT
country,
customer_name,
total_purchased,
RANK() OVER (PARTITIONED BY country ORDER BY total_purchased DESC) as rank
FROM total
) a
WHERE rank = 1
如果您不能使用分析功能,则可以执行以下操作:
SELECT a.country,
a.customer_name,
a.total_purchased
FROM total a
JOIN (
SELECT
country,
MAX(total_purchased) AS max_purchased
FROM total
GROUP BY country
) b
ON a.country = b.country
AND a.total_purchased = b.max_purchased
此查询应具有预期的结果。如果有2个客户具有相同的total_purchased价值。结果将显示两个客户。