add batch remove batch split batch comment selection show hidden batches hide batch highlight batch
db<>fiddle
donate feedback about
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
Help with an interesting Postgres question: Why isn't an Index Only Scan used on a partition accessed via the parent table?.
with raw_dataset as (
SELECT 123 as user_id, 1 as flag, 101 as updated_at
UNION ALL SELECT 123 as user_id, 0 as flag, 102 as updated_at
UNION ALL SELECT 123 as user_id, 1 as flag, 103 as updated_at
UNION ALL SELECT 123 as user_id, 1 as flag, 104 as updated_at
UNION ALL SELECT 123 as user_id, 1 as flag, 105 as updated_at
UNION ALL SELECT 124 as user_id, 0 as flag, 101 as updated_at
UNION ALL SELECT 124 as user_id, 0 as flag, 103 as updated_at
UNION ALL SELECT 124 as user_id, 0 as flag, 110 as updated_at
)
select rd.*,
max(case when prev_flag is null or prev_flag <> flag then updated_at end) over (
partition by user_id
order by updated_at
) as most_recent_updated_at
from (select rd.*,
lag(flag) over (partition by user_id order by updated_at) as prev_flag
from raw_dataset rd
) rd
user_id flag updated_at prev_flag most_recent_updated_at
123 1 101 null 101
123 0 102 1 102
123 1 103 0 103
123 1 104 1 103
123 1 105 1 103
124 0 101 null 101
124 0 103 0 101
124 0 110 0 101
SELECT 8