首页 > 解决方案 > 获取 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

标签: sqlsql-serveraggregate-functions

解决方案


使用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);

推荐阅读