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

How to connect two SQL tables with a condition

I have two tables (A & B).

I want all data from Table A. Table B has notes that reference the PKs from Table A via foreign key. I want to bring back all data from Table A and the most recent note ONLY from table B (there is a DateTime column in table B). I need all data from table A regardless if there is a note in Table B or not.

Thank you for any help.

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

>Solution :

SELECT 
    A.*, 
    B.Note
FROM 
    A
LEFT JOIN (
    SELECT 
        fk, 
        Note, 
        ROW_NUMBER() OVER (PARTITION BY fk ORDER BY InsertDate DESC) AS rn
    FROM 
        B
) B ON B.fk = A.pk AND B.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