Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dave-connors-3/6abeb5a9a985dd39af1fc66acbe8b3f4 to your computer and use it in GitHub Desktop.
Save dave-connors-3/6abeb5a9a985dd39af1fc66acbe8b3f4 to your computer and use it in GitHub Desktop.
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