简体   繁体   中英

How to create a materialized view for existing table in Timescale?

When I'm trying to create materialized view for existing table by query:

CREATE MATERIALIZED VIEW current_data_hourly
WITH (timescaledb.continuous) AS
SELECT id,
        time_bucket(INTERVAL  '1 hour', creation_time) AS creation_time,
       AVG(current_abs_1_avg),
       MAX(current_abs_1_max),
       MIN(current_abs_1_min)
FROM time_series.current_data
GROUP BY id, creation_time;

I'm getting:

ERROR:  continuous aggregate view must include a valid time bucket function
SQL state: XX000

Any suggestions what could be wrong?

In the view query above, the grouping is ambiguous between the input column name, which is creation_time in hypertable time_series.current_data , and the output column name, which is defined as time_bucket(INTERVAL '1 hour', creation_time) AS creation_time . According to GROUP BY description in SELECT documentation :

In case of ambiguity, a GROUP BY name will be interpreted as an input-column name rather than an output column name.

Ie, creation_time is not the one, which is alias for time_bucker expression. Thus the error.

One way to fix is to use the positions of the columns from the SELECT clause:

CREATE MATERIALIZED VIEW current_data_hourly
WITH (timescaledb.continuous) AS
SELECT id,
        time_bucket(INTERVAL  '1 hour', creation_time) AS creation_time,
       AVG(current_abs_1_avg),
       MAX(current_abs_1_max),
       MIN(current_abs_1_min)
FROM time_series.current_data
GROUP BY 1, 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM