我需要确定在每个国家/地区花费最多的客户,我要做的是获取每个客户的总支出,然后为该国家/地区的每个客户获取最大的支出,并加入两个表格, 我的问题是在英国国家/地区,有两个客户的总数相同,但是我的查询两次显示相同的客户(相同的customerId)。
SELECT t3.CustomerId, t3.FirstName, t3.LastName, t3.Country, t1.TotalSpent
FROM
(SELECT t2.CustomerId, t2.FirstName, t2.LastName, t2.Country, MAX(t2.CustomerTotal) AS maximum
FROM
(SELECT c.CustomerId, c.FirstName, c.LastName, c.Country,
Sum(i.Total) CustomerTotal
FROM Customer c
JOIN Invoice i
ON c.CustomerId = i.CustomerId
GROUP BY 1,2,3,4)t2
GROUP BY 4)t3
JOIN
(SELECT c.CustomerId, c.FirstName, c.LastName, c.Country, Sum(i.Total) TotalSpent
FROM Customer c
JOIN Invoice i
ON c.CustomerId = i.CustomerId
GROUP BY 1)t1
ON t1.TotalSpent= t3.maximum AND t1.Country = t3.Country
ORDER BY 4
我们有24个国家/地区,但输出应为25行,因为英国有2个客户共享最多的客户。