PostgreSQL
 SQL >> Database >  >> RDS >> PostgreSQL

Rimuovere i duplicati da una SELECT in PostgreSQL

Usa DISTINCT ON:

SELECT DISTINCT ON (contenthash)
       id, contenthash, filesize, to_timestamp(timecreated)::date
FROM mdl_files
ORDER BY contenthash, timecreated, id;

DISTINCT ON è un'estensione di Postgres che garantisce una sola riga per ogni combinazione univoca delle chiavi tra parentesi. La riga restituita è la prima secondo la clausola ORDER BY.

Come scegliere quale riga tenere

Qui l'ordinamento per timecreated, id mantiene l'occorrenza più vecchia. Invertendo l'ordine (ORDER BY contenthash, timecreated DESC, id DESC) conserverai invece la più recente. Senza un criterio univoco nell'ORDER BY la scelta tra righe equivalenti resta arbitraria.