Jeg foreslår den praktiske funktion width_bucket()
:
For at få gennemsnittet for hvert tidssegment ("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;
Sådan får du det "løbende gennemsnit" over det (trinvise) voksende tidsinterval:
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;
Brug af datoen
i stedet for dato
som kolonnenavn og undgå reserverede ord
som identifikatorer.
Siden width_bucket()
er i øjeblikket kun implementeret til dobbelt præcision
og numerisk
, udtrækker jeg epokeværdier fra the_date
. Detaljer her:
Aggregerende (x,y) koordinatpunktskyer i PostgreSQL