我有一个音乐商店的数据库,我需要提取特定于每个国家/地区的客户的最大购买价值。使用MAX
函数时,我注意到在“ United Kingdom”中有两个最大值的联系。因此,我需要查询以返回该国家/地区的两个客户。
With t1 As (
Select i.CustomerId, c.FirstName, c.LastName,
i.BillingCountry Country, Sum(i.Total) Totals
From Invoice i
Join Customer c
On c.CustomerId = i.CustomerId
GROUP BY 1, 4)
Select CustomerId, FirstName, LastName, Country, Max(Totals) TotalSpent
From t1
Group By 4;
这是输出
这应该是输出
我尝试使用TOP
,但显然按工作区,它不接受此功能。因此,请提出一种不使用此功能的解决方案。
谢谢。
答案 0 :(得分:0)
我会考虑类似的东西
With t1 As (
Select i.CustomerId, c.FirstName, c.LastName,
i.BillingCountry Country, Sum(i.Total) Totals
From Invoice i
Join Customer c
On c.CustomerId = i.CustomerId
GROUP BY 1, 4)
Select CustomerId, FirstName, LastName, Country, Totals TotalSpent
From t1
WHERE t1.Total = (SELECT MAX(Totals) FROM t1 t2 WHERE t1.Country = t2.Country)
Group By 4;
(我在主查询的MAX(Totals)
语句中将Totals
更改为SELECT
,并添加了WHERE
子句)
或
With t1 As (
Select i.CustomerId, c.FirstName, c.LastName,
i.BillingCountry Country, Sum(i.Total) Totals
From Invoice i
Join Customer c
On c.CustomerId = i.CustomerId
GROUP BY 1, 4),
t2 as (
SELECT Country, MAX(Totals) as Totals
FROM t1
GROUP BY Country
)
Select t1.CustomerId, t1.FirstName, t1.LastName, t1.Country, t1.Totals TotalSpent
From t1 INNER JOIN t2
on t1.Country = t2.Country and t1.Totals = t2.Totals
Group By 4;
(我添加了t2 CTE,将其加入到您的主查询中,并相应地调整了主SELECT
)
在两种情况下,我都试图选择所有客户信息,其中该客户的总数等于其所在国家/地区的最大总数。原则上,无论有多少关系,这都应该起作用。
答案 1 :(得分:0)
使用窗口功能!
select CustomerId, FirstName, LastName,
Country, Totals
from (select i.CustomerId, c.FirstName, c.LastName,
i.BillingCountry as Country, sum(i.Total) as Totals,
rank() over (partition by i.BillingCountry over sum(i.Total) desc) as seqnum
from Invoice i join
Customer c
on c.CustomerId = i.CustomerId
group by i.CustomerId, c.FirstName, c.LastName,
i.BillingCountry
) ic
where seqnum = 1;