By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE table_name (tran_dt) AS
SELECT date'2021-05-06' FROM dual UNION
SELECT date'2021-05-24' FROM dual UNION
SELECT date'2021-06-25' FROM dual UNION
SELECT date'2021-07-02' FROM dual UNION
SELECT date'2021-07-27' FROM dual UNION
SELECT date'2021-08-16' FROM dual UNION
SELECT date'2021-08-23' FROM dual UNION
SELECT date'2021-10-01' FROM dual UNION
SELECT date'2021-12-31' FROM dual
9 rows affected
ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';
SELECT tran_dt,
alert,
tran_dt
- LAG(CASE alert WHEN 'Yes' THEN tran_dt END, 1, tran_dt)
IGNORE NULLS OVER (ORDER BY tran_dt)
AS days
FROM table_name
MATCH_RECOGNIZE (
ORDER BY tran_dt
MEASURES
CLASSIFIER() AS alert
ALL ROWS PER MATCH
PATTERN ( "Yes" "No"* )
DEFINE
"No" AS tran_dt <= "Yes".tran_dt + INTERVAL '90' DAY
)
TRAN_DT | ALERT | DAYS |
---|---|---|
2021-05-06 00:00:00 | Yes | 0 |
2021-05-24 00:00:00 | No | 18 |
2021-06-25 00:00:00 | No | 50 |
2021-07-02 00:00:00 | No | 57 |
2021-07-27 00:00:00 | No | 82 |
2021-08-16 00:00:00 | Yes | 102 |
2021-08-23 00:00:00 | No | 7 |
2021-10-01 00:00:00 | No | 46 |
2021-12-31 00:00:00 | Yes | 137 |
WITH dates (tran_dt, rn) AS (
SELECT tran_dt,
ROW_NUMBER() OVER (ORDER BY tran_dt) AS rn
FROM table_name
),
rolling_dates (tran_dt, alert, rn, days, last_alert) AS (
SELECT tran_dt, 'Yes', rn, 0, tran_dt
FROM dates
WHERE rn = 1
UNION ALL
SELECT d.tran_dt,
CASE
WHEN d.tran_dt <= r.last_alert + INTERVAL '90' DAY
THEN 'No'
ELSE 'Yes'
END,
d.rn,
d.tran_dt - r.last_alert,
CASE
WHEN d.tran_dt <= r.last_alert + INTERVAL '90' DAY
THEN r.last_alert
ELSE d.tran_dt
END
FROM rolling_dates r
INNER JOIN dates d
ON (r.rn + 1 = d.rn)
)
SELECT tran_dt,
alert,
days
FROM rolling_dates;
TRAN_DT | ALERT | DAYS |
---|---|---|
2021-05-06 00:00:00 | Yes | 0 |
2021-05-24 00:00:00 | No | 18 |
2021-06-25 00:00:00 | No | 50 |
2021-07-02 00:00:00 | No | 57 |
2021-07-27 00:00:00 | No | 82 |
2021-08-16 00:00:00 | Yes | 102 |
2021-08-23 00:00:00 | No | 7 |
2021-10-01 00:00:00 | No | 46 |
2021-12-31 00:00:00 | Yes | 137 |