sql - 如何在我的查询中获得两个最大值的关系?
问题描述
我有一个音乐商店的数据库,我需要从每个国家/地区的特定客户那里提取购买的最大值。在使用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
但显然工作区不接受此功能。因此,请提出一个不使用此功能的解决方案。
提前致谢。
解决方案
使用窗口函数!
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;
推荐阅读
- python - K-means、词袋、Word嵌入文本分类CSV文件和检索数据关联
- dji-sdk - 仅在没有 GPS 的情况下控制 M100
- python - 多项式次数越高,多元线性回归不会变得更准确?
- azure-cosmosdb - 如何将多个输入传递给 cosmosdb 存储过程
- php - PDO/PHP 计数查询
- flutter - 如何使用 Google Places API 显示附近的位置作为颤振项目的列表(没有地图)?
- apache-spark - 使用 Airflow dag 运行 EMR 集群创建,一旦任务完成 EMR 将被终止
- reactjs - 获取请求后无法设置状态
- list - 使用 PowerShell 在文本文档中搜索包含关键字列表的大型文件夹
- tinymce - TinyMCE 4.9.x 仍然不能在 shadow dom 中工作。有什么想法可以解决吗?