De aanpak die bij mij opkwam, was om in plaats daarvan de afzonderlijke records te targeten die het label TRUE
zouden moeten krijgen. . Overweeg dit:
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;
Deze zoekopdracht lijkt te werken in de onderstaande demolink van Postgres.