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

SQL – select only latest record for each foreign key

Hello so my problem is basically, I have a table files like so:

foreign_key string created_at
1 "a" 2021-11-10
2 "b" 2021-11-15
2 "c" 2021-11-18

Now what I need is to select one record (string) for each distinct foreign_key and it always needs to be the latest (created_at)

I can’t use subquery in selects because of speed.

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

The result should look like this:

foreign_key string created_at
1 "a" 2021-11-10
2 "c" 2021-11-18

>Solution :

Using ROW_NUMBER:

WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY foreign_key
                                   ORDER BY created_at DESC) rn
    FROM yourTable t
)

SELECT foreign_key, string, created_at
FROM cte
WHERE rn = 1;

Another approach, using joins:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT foreign_key, MAX(created_at) AS max_created_at
    FROM yourTable
    GROUP BY foreign_key
) t2
    ON t2.foreign_key = t1.foreign_key AND
       t2.max_created_at = t1.created_at;
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