add batch remove batch split batch comment selection show hidden batches hide batch highlight batch
db<>fiddle
donate feedback about
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
Help with an interesting Postgres question: Why isn't an Index Only Scan used on a partition accessed via the parent table?.
create table pages (
date date,
pageviews int
);

insert into pages values
('2020-02-01'::date, 42),
('2020-02-02'::date, 3),
('2020-02-03'::date, 216),
('2020-02-04'::date, 186),
('2020-02-05'::date, 510),
('2020-02-06'::date, 419),
('2020-02-07'::date, 64),
('2020-02-09'::date, 230)
;

create table weights (
idx int,
weight float
);

insert into weights values
(0, 1/3.),
(1, 1/3.),
(2, 1/3.)
;




SELECT pages.date,
max(pages.pageviews) as pageviews,
CASE WHEN pages.date - (select min(date) from pages) >= 2 THEN sum(weight * ma_pages.pageviews) END as weighted_moving_average
FROM pages
JOIN pages AS ma_pages ON pages.date - ma_pages.date BETWEEN 0 AND 2
JOIN weights ON idx = pages.date - ma_pages.date
CREATE TABLE
INSERT 0 8
CREATE TABLE
INSERT 0 3
date pageviews weighted_moving_average
2020-02-01 42 null
2020-02-02 3 null
2020-02-03 216 87
2020-02-04 186 135
2020-02-05 510 304
2020-02-06 419 371.666666666667
2020-02-07 64 331
2020-02-09 230 98
SELECT 8