A abordagem que me veio à mente foi segmentar os registros individuais que devem ser rotulados como
TRUE
. Considere isto: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 no link de demonstração do Postgres fornecido abaixo.