我有一个名为 historic
的表:
create table historic
(
id serial not null
constraint table_name_pkey
primary key,
film_name varchar,
category varchar,
time_utc timestamp
)
;
create unique index table_name_id_uindex
on historic (id)
;
我还有另一个包含测量值
数据的表:
create table measurements
(
id serial not null
constraint measurements_pkey
primary key,
historic_rowid integer not null
constraint measurements_historic_id_fk
references historic,
measurement double precision
)
;
create unique index measurements_id_uindex
on measurements (id)
;
如您所见,measurements
表包含一个外键 historic_rowid
到 historic
表(在 rowid
).
我需要选择一个类别,比如 sci-fi
。然后,我想从 measurements
中选择与 sci-fi
类别匹配的所有记录并包括它们的时间:
SELECT h.film_name, h.category, m.measurement, h.time_utc
FROM historic h
LEFT JOIN measurements m on m.historic_rowid == h.id
WHERE h.category = 'sci-fi';
结果将是一个包含以下列的表格:
film_name, category, measurement, time_utc
现在,我想每 15 分钟计算一次此数据的平均值。换句话说,我想将我的数据“分类”为 15 分钟的时间间隔,然后为每个“分类”获取平均值。
我的最终结果将如下所示:
film_name, category, measurement, time_window
---------------------------------------------
film_a, sci-fi, 0.234234, 0_to_15
film_b, sci-fi, 0.692859, 15_to_30
film_c, sci-fi, 0.875854, 30_to_45
film_d, sci-fi, 0.583465, 45_to_60
film_e, sci-fi, 0.265334, 60_to_75
film_f, sci-fi, 0.152545, 75_to_90
....
我该怎么做?我不太懂 SQL,需要一些帮助。
更新
根据要求,这里是 time_utc 字段
的一些示例数据:
2017-04-18 02:31:03
2017-04-18 02:31:12
2017-04-18 02:31:27
2017-04-18 02:31:38
2017-04-18 02:31:53
2017-04-18 02:32:08
2017-04-18 02:32:17
2017-04-18 02:32:22
2017-04-18 02:32:58
2017-04-18 02:33:07
2017-04-18 02:33:12
2017-04-18 02:33:22
2017-04-18 02:33:37
2017-04-18 02:33:47
2017-04-18 02:34:32
2017-04-18 02:34:43
2017-04-18 02:34:47
2017-04-18 02:34:58
2017-04-18 02:35:02
2017-04-18 02:35:12
2017-04-18 02:35:17
2017-04-18 02:35:22
2017-04-18 02:35:32
2017-04-18 02:35:37
2017-04-18 02:35:42
2017-04-18 02:35:52
最佳答案
with m15 as (select generate_series('2017-04-18 00:00:00','2017-04-18 00:00:00','15 minutes'::interval) g)
SELECT h.film_name, h.category, avg(m.measurement), g
FROM historic h
LEFT JOIN measurements m on m.historic_rowid == h.id
join m15 on m15.g > time_utc and m15.g + '15 minutes'::interval < time_utc
WHERE h.category = 'sci-fi'
group by h.film_name, h.category, g
当然,如果你想包含空间隔,join 可能需要是 outer join。并且您需要为 generate_series 定义最小值和最大值 - 可以使用 select min(time_utc) and max(time_utc)
关于postgresql - 我怎样才能每 15 分钟平均一次这些数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45794245/