Suggerisco la pratica funzione width_bucket()
:
Per ottenere la media per ciascun segmento di tempo ("bin"):
SELECT width_bucket(extract(epoch FROM t.the_date)
, x.min_epoch, x.max_epoch, x.bins) AS bin
, avg(value) AS bin_avg
FROM tbl t
, (SELECT extract(epoch FROM min(the_date)) AS min_epoch
, extract(epoch FROM max(the_date)) AS max_epoch
, 10 AS bins
FROM tbl t
) x
GROUP BY 1;
Per ottenere la "media corrente" sull'intervallo di tempo crescente (passo dopo passo):
SELECT bin, round(sum(bin_sum) OVER w /sum(bin_ct) OVER w, 2) AS running_avg
FROM (
SELECT width_bucket(extract(epoch FROM t.the_date)
, x.min_epoch, x.max_epoch, x.bins) AS bin
, sum(value) AS bin_sum
, count(*) AS bin_ct
FROM tbl t
, (SELECT extract(epoch FROM min(the_date)) AS min_epoch
, extract(epoch FROM max(the_date)) AS max_epoch
, 10 AS bins
FROM tbl t
) x
GROUP BY 1
) sub
WINDOW w AS (ORDER BY bin)
ORDER BY 1;
Usando the_date
invece di date
come nome della colonna, evitando parole riservate
come identificatori.
Da width_bucket()
è attualmente implementato solo per double precision
e numeric
, estraggo i valori epoch da the_date
. Dettagli qui:
Aggregazione di nuvole di punti di coordinate (x,y) in PostgreSQL