SELECT device.uuid AS device_id, device.space_device_uuid AS space_id, -- Mark none_flag if value is 'none' CASE WHEN "device-status-log".value = 'none' THEN 1 ELSE 0 END AS none_flag, "device-status-log".event_time::timestamp AS event_time, LAG("device-status-log".event_time::timestamp) OVER (PARTITION BY device.uuid ORDER BY "device-status-log".event_time) AS prev_timestamp, LAG( CASE WHEN "device-status-log".value = 'none' THEN 1 -- identifies if there was a 'none' flag detected ELSE 0 END ) OVER (PARTITION BY device.uuid ORDER BY "device-status-log".event_time) AS prev_none_flag FROM device LEFT JOIN "device-status-log" ON device.uuid = "device-status-log".device_id LEFT JOIN product ON product.uuid = device.product_device_uuid WHERE product.cat_name = 'hps' AND "device-status-log".code = 'presence_state' ORDER BY device.uuid, "device-status-log".event_time