Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum of value taking distinct ID and latest date

My table goes like

ID       Date        Value

ID1     01.01.2022    10

ID1     01.02.2022    10

ID1     01.03.2022    20

ID1     01.04.2022    30

ID2     01.01.2022    20

Expected result – 50 (Value 30 for ID1 with date 1.04.2022 + Value 20 from ID2)

I know I can get such table (with only ID1 last date and ID2 last date) using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT ID, VALUE, DATE FROM ( 
SELECT *, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DATE ASC)
 AS ROWNUM 
FROM "Table") X 
WHERE ROWNUM = 1

but dont now how to SUM (Value) in this. Could you help me?

>Solution :

You are on the right track. You should use ROW_NUMBER in a subquery to identify the latest row for each ID value. Then sum the value over that intermediate table.

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC) rn
    FROM yourTable
)

SELECT SUM(Value) AS Total
FROM cte
WHERE rn = 1;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading