Skip to content
Advertisement

select current address

I am new in sql and have a table as folow:

patientid  |gender|yearbirth|zipcode|admission          |
-----------|------|---------|-------|-------------------|
P1213060727|w     |     1926|55268  |2017-01-23 16:28:00|
P1213060727|w     |     1926|55270  |2018-09-26 18:10:00|
P1213060729|w     |     1956|55262  |2018-03-09 09:51:00|
P1213060731|m     |     1935|55276  |2015-02-11 16:54:00|
P1213060762|w     |     1945|55452  |2011-01-19 15:30:00|

Some person have two address and I need the list of patients with the current address.

patientid  |gender|yearbirth|zipcode|
-----------|------|---------|-------|
P1213060727|w     |     1926|55270  |
P1213060729|w     |     1956|55262  |
P1213060731|m     |     1935|55276  |
P1213060762|w     |     1945|55452  |

Advertisement

Answer

You can solve this greatest-n-per-group problem with distinct on:

select distinct on(patientId) t.*
from mytable t
order by patientId, admission desc
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement