sql - 获取 Max(Amount) 和关联的类型
问题描述
我有以下查询返回正确的值,但我还需要获取该行的关联收入类型。得到这个的最好方法是什么,如果表中还有其他字段,我怎么能得到这些呢?
select
PersonID,
max(Amount)
from #Temp
group by
PersonID
样本数据:
Create Table #Temp
(
ID int,
PersonID int,
IncomeType varchar(50),
Amount money
)
insert into #Temp
(
ID,
PersonID,
IncomeType,
Amount
)
select
1,
1,
'IncomeType1',
50
union all
select
2,
1,
'IncomeType2',
35
union all
select
3,
1,
'IncomeType3',
75
union all
select
4,
1,
'IncomeType4',
17
union all
select
5,
2,
'IncomeType1',
100
union all
select
6,
2,
'IncomeType2',
76
解决方案
使用ROW_NUMBER
:
SELECT TOP 1 WITH TIES ID, PersonID, IncomeType, Amount
FROM #Temp
ORDER BY ROW_NUMBER() OVER (PARTITION BY PersonID ORDER BY Amount DESC);
推荐阅读
- python - Django 查询互相喜欢的用户
- java - 有什么方法可以返回 Flux
从 Spring REST 端点到 Web 浏览器/前端应用程序(即 Angular 6)? - django-rest-framework - 如何编写允许在 url 本身中放置值的 API
- c# - Winforms 双向数据绑定不会正确更新 UI,除非执行一些其他 UI 操作
- mysql - 了解 Sequelize 中的关联
- c# - rfc822 格式的电子邮件地址有没有好的解析器
- php - 如何在每一行上添加一个按钮
- python - 从 GridFs file_id 或 GridFSProxy 创建 Mongoengine FileField
- opencv - 图像经过Canny算子处理后如何获取边缘位置的像素坐标
- windows - git stage hunk 在 git for Windows 上的工作方式不同吗?