如何在查询中间的列上执行非重复

时间:2019-05-06 18:05:30

标签: sql

我正在尝试(在国家/地区)列上执行(区别)或其他任何操作相同的操作,但是这不起作用,这就是我遇到的问题

ListenableWorker

1 个答案:

答案 0 :(得分:0)

WITH t1 AS 
(
    SELECT c.Country, SUM(i.Total) TotalSpent, c.FirstName, c.LastName, c.CustomerId
    FROM 
        Customer c
        JOIN Invoice i ON c.CustomerId = i.CustomerId
    GROUP BY c.CustomerId
)

SELECT t1.*
FROM t1
JOIN(
    SELECT Country, MAX(TotalSpent) AS MaxTotalSpent, FirstName, LastName, CustomerId
    FROM t1
    GROUP BY Country
)t2
ON t1.Country = t2.Country
WHERE t1.TotalSpent = t2.MaxTotalSpent
ORDER BY Country;