Saya menyarankan fungsi praktis width_bucket()
:
Untuk mendapatkan rata-rata untuk setiap segmen waktu ("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;
Untuk mendapatkan "rata-rata berjalan" selama interval waktu pertumbuhan (langkah demi langkah):
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;
Menggunakan the_date
bukannya date
sebagai nama kolom, hindari kata-kata khusus
sebagai pengenal.
Sejak width_bucket()
saat ini hanya diimplementasikan untuk double precision
dan numeric
, saya mengekstrak nilai Epoch dari the_date
. Detailnya di sini:
Menggabungkan (x,y) awan titik koordinat di PostgreSQL