sql >> Database teknologi >  >> RDS >> PostgreSQL

PostgreSQL Valg af Seneste Indgang for et givet ID

Der er omkring 5 forskellige måder at gøre dette på, men her er en:

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

Og her er en anden:

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

En mere:

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, jeg bliver revet med, her er den sidste, jeg vil poste (indtil videre):

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


  1. Android - Cursor onMapReady (Markører)

  2. Kontrollerer, om et element ikke findes i en anden tabel

  3. Eksporter forespørgselsresultater til en XML-fil, når du bruger SQLcl (Oracle)

  4. Hibernate:Opretter/opdaterer automatisk db-tabellerne baseret på entitetsklasser