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

Valg af rækker ordnet efter en kolonne og adskilt i en anden

Helt klart spørgsmål :)

SELECT t1.* FROM purchases t1
LEFT JOIN purchases t2
ON t1.address_id = t2.address_id AND t1.purchased_at < t2.purchased_at
WHERE t2.purchased_at IS NULL
ORDER BY t1.purchased_at DESC

Og højst sandsynligt en hurtigere tilgang:

SELECT t1.* FROM purchases t1
JOIN (
    SELECT address_id, max(purchased_at) max_purchased_at
    FROM purchases
    GROUP BY address_id
) t2
ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at
ORDER BY t1.purchased_at DESC


  1. Sådan beregnes glidende gennemsnit i rødforskydning

  2. Dynamisk pivot i oracle sql

  3. Hvorfor postgres ikke bruger indekset i min forespørgsel

  4. Slet med Left Join i Oracle 10g