我可以在同一查询中使用 BETWEEN 和 IN 子句指定多个间隔吗?
Can i specify multiple intervals using BETWEEN and IN clause in the same query?
我正在查询一些时间序列数据,并希望将查询应用于多个指定的时间间隔,以便为每个间隔获取不同的行。
我的意思是:
这些是时间间隔(不要看空的,要使用 coalesce()
):
并想像这样查询我的数据:
select count(*) from time_series where time between [multiple_intervals_here]
我最接近的解决方案是:
select count(*) from time_series where time (between x and y) or (between a and b)
但显然,我无法动态指定间隔 并且不会为每个间隔获取一行。
(我将对其应用更多聚合函数,而不仅仅是count()
)
最终结果如下所示:
提前致谢
对每个区间进行单独查询并合并结果
select 'interval 1' as interval, count(*) from time_series where time between A and B
union
select 'interval 2' as interval, count(*) from time_series where time between C and D
union
select 'interval 3' as interval, count(*) from time_series where time between E and F
t
CTE 是间隔列表的模仿。
with t (id, time_start, time_stop) as
(
values
('interval-A', '2022-05-26T10:00'::timestamp, '2022-05-26T12:00'::timestamp),
('interval-B', '2022-05-26T13:00', '2022-05-26T17:00')
)
select t.id, count(l.x) as "count", avg(l.x) as "avg"
from t
cross join lateral
(
select x from the_table tt
where tt.start_time between t.time_start and t.time_stop
and tt.end_time between t.time_start and t.time_stop
) l
group by t.id;
我正在查询一些时间序列数据,并希望将查询应用于多个指定的时间间隔,以便为每个间隔获取不同的行。
我的意思是:
这些是时间间隔(不要看空的,要使用 coalesce()
):
并想像这样查询我的数据:
select count(*) from time_series where time between [multiple_intervals_here]
我最接近的解决方案是:
select count(*) from time_series where time (between x and y) or (between a and b)
但显然,我无法动态指定间隔 并且不会为每个间隔获取一行。
(我将对其应用更多聚合函数,而不仅仅是count()
)
最终结果如下所示:
提前致谢
对每个区间进行单独查询并合并结果
select 'interval 1' as interval, count(*) from time_series where time between A and B
union
select 'interval 2' as interval, count(*) from time_series where time between C and D
union
select 'interval 3' as interval, count(*) from time_series where time between E and F
t
CTE 是间隔列表的模仿。
with t (id, time_start, time_stop) as
(
values
('interval-A', '2022-05-26T10:00'::timestamp, '2022-05-26T12:00'::timestamp),
('interval-B', '2022-05-26T13:00', '2022-05-26T17:00')
)
select t.id, count(l.x) as "count", avg(l.x) as "avg"
from t
cross join lateral
(
select x from the_table tt
where tt.start_time between t.time_start and t.time_stop
and tt.end_time between t.time_start and t.time_stop
) l
group by t.id;