Nice puzzle :-)
This should work, there are probably other solutions, but this one needs only a single STAT fubnction step:
SELECT
maturity,
timeperiod,
COUNT(CASE WHEN timeperiod <= maturity THEN 1 END) OVER (PARTITION BY maturity) AS cnt1,
COUNT(CASE WHEN timeperiod > maturity THEN 1 END) OVER (PARTITION BY maturity) AS cnt2,
ROW_NUMBER() OVER (PARTITION BY maturity ORDER BY timeperiod) AS rn,
rn - CASE
WHEN cnt1 > 0 AND cnt2 > 0 THEN cnt1 -1
WHEN cnt1 > 0 THEN cnt1-2
ELSE cnt1
END AS x
FROM tab
QUALIFY x IN (1,2)
Dieter
↧