0

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!

6
  • What happens if there is a record for user_id 1 on 2021-10-04 that has a level of 3? Would the level_achieved for the purchase records for user 1 both be 5, or would one be 3 and one be 5?
    – dfundako
    Commented Aug 4, 2023 at 17:46
  • You could try the window function LAST_VALUE() and if you partition that by user_id and order that by Date, you should be able to get what you want.
    – Josh
    Commented Aug 4, 2023 at 17:47
  • @dfundako it should be one with 3 and another one with 5
    – Smasell
    Commented Aug 4, 2023 at 17:49
  • @josh No, it's not working, because some purchases can happen twice in one level.
    – Smasell
    Commented Aug 4, 2023 at 17:51
  • I think you have to specify IGNORE NULLS ... but I like Mustafa's answer better with the subquery
    – Josh
    Commented Aug 4, 2023 at 18:03

2 Answers 2

3

Assuming that level can't go down you can use just max which will ignore null's:

SELECT *,
    if(value is null, max(value) over(partition by user_id order by date)) level_achieved
FROM my_table;

Output:

user_id date event_name value level_achieved
1 2021-10-01 level 5 NULL
1 2021-10-03 purchase NULL 5
1 2021-10-05 purchase NULL 5
2 2021-10-02 level 10 NULL
2 2021-10-03 purchase NULL 10

Or using last_value with ignore nulls option:

SELECT *,
    if(value is null, last_value(value) IGNORE NULLS over(partition by user_id order by date)) level_achieved
FROM my_table;
1

I would advise you to create a subquery with the following:

user_id, level, date as date_start, lead(date) over(partition by user_id order by date asc) as date_end
(where level is not null)

You will get a structure like:

user_id, level, date_start, date_end

Next you can join with:

        my_table ON my_table.date >= sub_query.date_start 
    AND my_table.date < sub_query.date_end
AND my_table.user_id = sub_query.user_id

With this you can easily get the level for that specific date range.

Good luck

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.