In a table, I have events showing values (x
) for things with different IDs at different event timestamps.
WITH
events AS (
SELECT 1 AS thing_id, 1 AS x, TIMESTAMP('2021-12-01 00:00:00') AS event_timestamp
UNION ALL
SELECT 1, 3, TIMESTAMP('2021-12-01 00:01:00')
UNION ALL
SELECT 2, 5, TIMESTAMP('2021-12-01 00:02:00')
UNION ALL
SELECT 1, 0, TIMESTAMP('2021-12-01 00:03:00'))
SELECT
* FROM events
---------- --- ---------------------
| thing_id | x | event_timestamp |
---------- --- ---------------------
| 1 | 1 | 2021-12-01 00:00:00 |
| 1 | 3 | 2021-12-01 00:01:00 |
| 2 | 5 | 2021-12-01 00:02:00 |
| 1 | 0 | 2021-12-01 00:03:00 |
---------- --- ---------------------
I'd like to obtain a history showing the sum of all current x
values for each known event_timestamp
.
--------------------- -------
| event_timestamp | x_sum |
--------------------- -------
| 2021-12-01 00:00:00 | 1 |
| 2021-12-01 00:01:00 | 3 |
| 2021-12-01 00:02:00 | 8 |
| 2021-12-01 00:03:00 | 5 |
--------------------- -------
What would the needed SQL statement look like? I'm trying to think about grouping per thing_id
, windowing, and maybe cross joining on all event_timestamp
s, but I can't figure it out.
CodePudding user response: