El enfoque que me vino a la mente fue apuntar a los registros individuales que deberían etiquetarse como TRUE
. Considere esto:
WITH cte AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY phone ORDER BY ts) rn
FROM notifications n1
WHERE EXISTS (SELECT 1 FROM notifications n2 WHERE n1.phone = n2.phone AND
n2.ts < n1.ts AND n2.status = 'SUB' AND n2.result = 'SUCCESS') AND
n1.status = 'RENEWAL' AND n1.result = 'SUCCESS'
)
SELECT n1.*,
CASE WHEN n2.rn = 1 THEN 'TRUE'
WHEN n2.rn > 1 THEN 'FALSE' END AS is_first_renewal
FROM notifications n1
LEFT JOIN cte n2
ON n1.phone = n2.phone AND n1.ts = n2.ts;
Esta consulta parece estar funcionando en el enlace de demostración de Postgres que se proporciona a continuación.