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

generate_series in Postgres a partire da data di inizio e fine in una tabella

Non ti serve una CTE: sarebbe più costoso del necessario.
E non serve fare il cast a timestamp: il risultato è già di tipo timestamp quando passi tipi timestamp a generate_series(). Dettagli qui:

  • Generating time series between two dates in PostgreSQL

In Postgres 9.3 o successivo puoi usare una LATERAL join:

SELECT to_char(ts, 'YYYY-MM-DD HH24') AS formatted_ts FROM ( SELECT min(start_timestamp) as first_date , max(start_timestamp) as last_date FROM header_table ) h , generate_series(h.first_date, h.last_date, interval '1 hour') g(ts); 

Eventualmente con to_char() per ottenere il risultato come testo nel formato che hai menzionato.

Questo funziona in qualsiasi versione di Postgres:

SELECT generate_series(min(start_timestamp) , max(start_timestamp) , interval '1 hour') AS ts FROM header_table; 

Di solito un po' più veloce.
Chiamare funzioni che restituiscono insiemi nella lista della SELECT è una funzionalità non standard SQL e vista con disapprovazione da alcuni. Inoltre c'erano stranezze comportamentali (non in questo caso semplice) poi risolte in Postgres 10. Vedi:

  • What is the expected behaviour for multiple set-returning functions in SELECT clause?

Nota una sottile differenza nella gestione dei NULL:

L'equivalente di

max(start_timestamp) 

si ottiene con

ORDER BY start_timestamp DESC NULLS LAST LIMIT 1

Senza NULLS LAST i valori NULL vengono prima nell'ordinamento decrescente (se start_timestamp può contenere NULL). Otterresti NULL per last_date e la tua query non restituirebbe nulla.

Dettagli:

  • Why do NULL values come first when ordering DESC in a PostgreSQL query?