【问题标题】:How to downsample timeseries data with many columns in SQL?如何在 SQL 中对具有多列的时间序列数据进行下采样?
【发布时间】:2019-10-22 09:41:21
【问题描述】:

我正在运行一个 postgresql 数据库(也使用 timescaledb,用于 grafana),并且已经学会了如何使用以下方法对简单表进行下采样:

CREATE VIEW my_view
WITH (timescaledb.continuous) --Makes the view continuous
AS
SELECT
  time_bucket('1 min', time) as bucket,
  avg(sensor1),
  avg(sensor2),
  avg(sensor3)
FROM
  my_table
GROUP BY bucket;

此代码创建一个包含三个传感器的 VIEW,并将采样率从(例如)1 秒采样率降低到 1 分钟采样率。

这一切都很好,直到我有一个包含数百列的表,我希望对其进行下采样。我不想写出这段代码,数百个平均值显式出现在每个传感器的查询中。我希望 postgresql 有一种方法可以将我的平均聚合一次应用于表的所有列。

我已经在谷歌上搜索了很长一段时间的答案,这是我能找到的最接近的答案,虽然不是完全相同的问题:

select aggregate function and all other columns

我尝试使用语法 avg(*),但收到语法错误。

CREATE VIEW my_view
WITH (timescaledb.continuous) --Makes the view continuous
AS
SELECT
  time_bucket('1 min', time) as bucket,
  avg(sensor1),
  avg(sensor2),
  avg(sensor3)
FROM
  my_table
GROUP BY bucket;

另一个尝试是

CREATE VIEW my_view
WITH (timescaledb.continuous) --Makes the view continuous
AS
SELECT
  time_bucket('1 min', time) as bucket,
  avg(*)
FROM
  my_table
GROUP BY bucket;

语法错误。

我希望有一种方法可以执行此查询,而无需为每个传感器编写跨越数百行的代码。感谢您的帮助。

【问题讨论】:

    标签: database postgresql aggregation timescaledb


    【解决方案1】:

    可以使用目录表生成查询,然后在psql中用\gexec执行,

    一个例子是

    with avgs as (
       select string_agg('avg('||attname||')', ', ') as avg_text 
       from pg_attribute where attrelid ='my_table'::regclass
    )·
    select format(
    $$·
      CREATE VIEW my_view
      WITH (timescaledb.continuous) --Makes the view continuous
      AS
      SELECT
        time_bucket('1 min', time) as bucket,
        %s                                                                                                                                                
    FROM  my_table
    GROUP BY bucket;
    $$, 
    avg_text) 
    FROM avgs
    \gexec
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-26
      • 2021-10-01
      • 2017-11-18
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      相关资源
      最近更新 更多