首页 > 解决方案 > 如何在我的查询中获得两个最大值的关系?

问题描述

我有一个音乐商店的数据库,我需要从每个国家/地区的特定客户那里提取购买的最大值。在使用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但显然工作区不接受此功能。因此,请提出一个不使用此功能的解决方案。

提前致谢。

标签: sqlmaxaggregation

解决方案


使用窗口函数!

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;

推荐阅读