SQL QUERY
select id, month_id, id_type,
max(case when immediate_prev <> id_type then immediate_prev
end) over (partition by id, id_type, (seqnum - seqnum_2)
) as id_type_prev
from (select *,
row_number() over (partition by id order by month_id) as seqnum,
row_number() over (partition by id, id_type order by month_id) as seqnum_2,
lag(id_type) over (partition by id order by month_id) as immediate_prev
from `my_table`
WHERE id = 123
)
ORDER BY month_id asc
my_table data
id|month_id|id_type
123|202001|aaa
123|202002|aaa
123|202003|aaa
123|202004|bbb
123|202005|bbb
123|202006|bbb
Query return data
id|month_id|id_type|id_type_prev
123|202001|aaa|null
123|202002|aaa|null
123|202003|aaa|null
123|202004|bbb|aaa
123|202005|bbb|aaa
123|202006|bbb|aaa
I have a SQL query that returns the previous id_type value for a given id. I would also like to know the month_id of the previous id_type but I am not sure how to get this information. Above is the table data and what my current query returns.
Below is the additional data I am after, I woud like help getting the month_id_prev added to my above query. This would be the previous id_type's most recent month_id.
id|month_id|id_type|id_type_prev|month_id_prev
123|202001|aaa|null|null
123|202002|aaa|null|null
123|202003|aaa|null|null
123|202004|bbb|aaa|202003
123|202005|bbb|aaa|202003
123|202006|bbb|aaa|202003
