The following account closed on 1/19/2018, then reopened on 2/27/2018, then closed again on 3/26/2018. How do I write the sql to capture when this account was opened and closed. The closerestrictind = 'C' is when the account was closed.
We are working in a data warehouse where the data is loaded everyday to capture all the history.
It should look like this for acct 1234:
closed on 1/19/2018
re-opened on 2/27/2018
closed on 3/26/2018
Thank you!
You can use lag()
:
select acctnbr, effectivedate,
(case when closerestrictedind = 'C' then 'closed' else 'opened' end) as action
from (select t.*, lag(closerestrictedind) over (partition by acctnbr order by effectivedate) as prev_cr
from t
) t
where prev_cr <> closerestrictedind;
You can do two select statements, the first one with row_number() partition by acctnbr, order by date... save it in tmp table
The second select, inner join this table with itself, t1 and t2.
Where t1.closerestrictedind = 'C'
And the join where t1.rownum > t2.rownum +1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.