BigQuery materialized view - last in group

Viewed 999

In BigQuery Is it possible to create a materialized view containing the latest row for each group in a base table.

e.g.

CREATE TABLE basetable (
  group_id INT64, timestamp TIMESTAMP, value FLOAT64
);

INSERT INTO basetable (group_id, timestamp, value) VALUES
(1, '2020-01-01', 0.1), 
(1, '2020-01-02', 0.2),
(2, '2020-01-02', 0.1),
(2, '2020-01-01', 0.2);
Base table
+----------+--------------+-------+
| group_id | timestamp    | value |
+----------+--------------+-------+
|    1     | '2020-01-01' |   0.1 |
|    1     | '2020-01-02' |   0.2 |
|    2     | '2020-01-02' |   0.1 |
|    2     | '2020-01-01  |   0.2 |
+----------+--------------+-------+

I'd like materialized view to look as follows

Materialized view 
+----------+--------------+-------+
| group_id | timestamp    | value |
+----------+--------------+-------+
|    1     | '2020-01-02' |   0.2 |
|    2     | '2020-01-02' |   0.1 |
+----------+--------------+-------+

BigQuery materialized views do not support analytical functions or joins. Is there any other way to create such a view?

2 Answers

You can do that at most like this, be advised that the result is an Array with one item

CREATE MATERIALIZED VIEW  name as
SELECT group_id,
max(t.timestamp) as timestamp,
ARRAY_AGG(t.value  IGNORE NULLS ORDER BY t.timestamp DESC LIMIT 1) as value 
FROM table t
group by group_id

then you need a view as well

create view viewname as
SELECT group_id,timestamp
cast(value [safe_offset(0)] as string) as  value 
FROM materialized_view

You could use a single query with exists logic to ensure that the most recent record for each group_id is selected:

SELECT group_id, timestamp, value
FROM yourTable t1
WHERE NOT EXISTS (SELECT 1 FROM yourTable t2
                  WHERE t2.group_id = t1.group_id AND t2.timestamp > t1.timestamp);

I cannot think of any way to get the result set you want without using either analytic functions or a subquery of some kind. The above might be the leanest option here, without using analytic functions.

Related