Created
May 9, 2022 21:52
-
-
Save dave-connors-3/6abeb5a9a985dd39af1fc66acbe8b3f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source_data as ( | |
select | |
'DAVE' as name, | |
'LAPTOP' as device, | |
'2022-03-04'::date as load_date | |
union all | |
select | |
'DAVE' as name, | |
'LAPTOP' as device, | |
'2022-03-05'::date as load_date | |
union all | |
select | |
'DAVE' as name, | |
'CELL' as device, | |
'2022-09-21'::date as load_date | |
union all | |
select | |
'SAM' as name, | |
'LAPTOP' as device, | |
'2022-03-09'::date as load_date | |
union all | |
select | |
'SAM' as name, | |
'CELL' as device, | |
'2022-10-21'::date as load_date | |
union all | |
select | |
'DAVE' as name, | |
'LAPTOP' as device, | |
'2022-10-21'::date as load_date | |
), | |
process_changes as ( | |
select | |
*, | |
coalesce(device != lag(device) over ( | |
partition by name | |
order by load_date asc | |
) | |
, TRUE) as is_device_switch | |
from source_data | |
), | |
windowed as ( | |
select | |
name, | |
device, | |
load_date as valid_to_ts, | |
lead(load_date) over ( | |
partition by name | |
order by load_date asc | |
) | |
as valid_to_current | |
from process_changes | |
where is_device_switch | |
) | |
select * from windowed order by name, valid_to_ts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment