I have my table like this:
WITH
my_table (user_id, date, event_name, value) AS (
values
(1,'2021-10-01', 'level', 5),
(1,'2021-10-03', 'purchase', null),
(1,'2021-10-05', 'purchase', null),
(2,'2021-10-02', 'level', 10),
(2,'2021-10-03', 'purchase', null)
)
SELECT *
FROM my_table
user_id | date | event_name | level |
---|---|---|---|
1 | 2021-10-01 | level | 5 |
1 | 2021-10-03 | purchase | |
1 | 2021-10-05 | purchase | |
2 | 2021-10-02 | level | 10 |
2 | 2021-10-03 | purchase |
All I want is to add column with the last level
achieved before every purchase for every user_id
.
Desired table should look like this
user_id | date | event_name | level | level_achieved |
---|---|---|---|---|
1 | 2021-10-01 | level | 5 | |
1 | 2021-10-03 | purchase | 5 | |
1 | 2021-10-05 | purchase | 5 | |
2 | 2021-10-02 | level | 10 | |
2 | 2021-10-03 | purchase | 10 |
Thanks for helping me!
2
Answers
I would advise you to create a subquery with the following:
You will get a structure like:
Next you can join with:
With this you can easily get the level for that specific date range.
Good luck
Assuming that level can’t go down you can use just
max
which will ignorenull
‘s:Output:
Or using
last_value
withignore nulls
option: