我有一个音乐商店的数据库,我需要从特定于每个国家的客户那里提取购买的最大价值。在使用MAX函数时,我注意到我在‘英国’有两个最大值的关系。因此,我需要我的查询返回这个国家/地区的两个客户。
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,但显然workspace不接受此功能。所以,请推荐一个不使用此函数的解决方案。
提前谢谢。
发布于 2019-06-14 12:04:46
我会考虑像这样的事情
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;(我已经在主查询的SELECT语句中将MAX(Totals)更改为Totals,并添加了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 )
在这两种情况下,我都会尝试选择该客户的合计等于其所在国家/地区的最大合计的所有客户信息。原则上,无论有多少联系,这都应该是可行的。
发布于 2019-06-14 20:02:36
使用窗口函数!
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;https://stackoverflow.com/questions/56590878
复制相似问题