Den tilgang, jeg kom til at tænke på, var i stedet at målrette mod de individuelle poster, som skulle mærkes som TRUE
. Overvej dette:
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;
Denne forespørgsel ser ud til at virke i Postgres-demolinket nedenfor.