By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE Test(AA varchar(20),BB varchar(20),CC varchar(20),DD integer,EE integer);
insert into Test values ('201902','X','1000',1,1);
insert into Test values ('201902','X','1000',2,2);
insert into Test values ('201902','X','1001',4,3);
insert into Test values ('201902','Y','2000',6,4);
insert into Test values ('201902','Y','2001',8,5);
insert into Test values ('201903','Y','2002',10,6);
insert into Test values ('201904','Y','2002',12,7);
select *
from Test
where 1=1
order by AA,BB;
AA | BB | CC | DD | EE |
---|---|---|---|---|
201902 | X | 1000 | 1 | 1 |
201902 | X | 1000 | 2 | 2 |
201902 | X | 1001 | 4 | 3 |
201902 | Y | 2000 | 6 | 4 |
201902 | Y | 2001 | 8 | 5 |
201903 | Y | 2002 | 10 | 6 |
201904 | Y | 2002 | 12 | 7 |
select AA,BB,SUM(DD) AS DD
From (
select AA,BB,CC,DD,ROW_NUMBER() OVER (PARTITION BY AA,BB,CC ORDER BY EE desc) AS KK
from Test) AS SS
Where KK = 1
Group By AA,BB
AA | BB | DD |
---|---|---|
201902 | X | 6 |
201902 | Y | 14 |
201903 | Y | 10 |
201904 | Y | 12 |