sql >> Base de Datos >  >> RDS >> PostgreSQL

PostgreSQL seleccionando la entrada más reciente para una identificación dada

Hay alrededor de 5 formas diferentes de hacer esto, pero aquí hay una:

SELECT *
FROM yourTable AS T1 
WHERE NOT EXISTS(
    SELECT *
    FROM yourTable AS T2
    WHERE T2.ID = T1.ID AND T2.Date > T1.Date
)

Y aquí hay otro:

SELECT T1.*
FROM yourTable AS T1
LEFT JOIN yourTable AS T2 ON
(
    T2.ID = T1.ID 
    AND T2.Date > T1.Date
)
WHERE T2.ID IS NULL

Uno más:

WITH T AS (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Date DESC) AS rn
    FROM yourTable
)
SELECT * FROM T WHERE rn = 1

Ok, me estoy dejando llevar, aquí está el último que publicaré (por ahora):

WITH T AS (
    SELECT ID, MAX(Date) AS latest_date
    FROM yourTable
    GROUP BY ID
)
SELECT yourTable.*
FROM yourTable
JOIN T ON T.ID = yourTable.ID AND T.latest_date = yourTable.Date