假设您有两个ID
ID1 ID2 SUM
01 A 1,000
01 B 2,000
01 C 3,000
02 AA 500
02 BB 6,000
我正在尝试获得ID1和ID2,其中总和是最大值,即。,
ID1 ID2 SUM
01 C 3,000
02 BB 6,000
我不确定如何编写此查询。
答案 0 :(得分:0)
用于SQL-Server
declare @mytable as table (id1 int, id2 varchar(10), sum_ money)
insert into @mytable
values
(01, 'A', 1000),
(01, 'B', 2000),
(01 , 'C', 3000),
(02, 'AA', 500),
(02, 'BB', 6000)
select t.*
from @mytable t
join ( --- get id1 and max sum
select
id1,max(sum_) sum_
from @mytable
group by id1
) x on x.id1 = t.id1 and x.sum_ = t.sum_ --- match id1 and max sum to the original table
order by t.id1