I run a query in postgresql to obtain the category of paydays in t+1 (f.e.02-28-2015) of a set of clients on a cut-off date - previous month t (f.e.01-31-2015). The result is satisfactory, however, if I wanted the rolls rate from January 2015 to January 2020, I have to run month by month, changing the month t and month t +1. They know somehow to obtain the result with a single execution of a querie, maybe a loop. Thanks in advance.
--creating the categories for month t plus 1 (Feb15)
DROP TABLE IF EXISTS rolls_rate_t_plus_1;
CREATE TEMP TABLE rolls_rate_t_plus_1 AS (SELECT
a.co_contra -- Primary key
,a.pe_produc -- Month of production
, (CASE
WHEN a.co_diamorcro <= 0 THEN '0 dpd'
WHEN a.co_diamorcro > 0 AND a.co_diamorcro <= 8 THEN '1-8 dpd'
WHEN a.co_diamorcro > 8 AND a.co_diamorcro <= 30 THEN '9-30 dpd'
WHEN a.co_diamorcro > 30 AND a.co_diamorcro <= 60 THEN '31-60 dpd'
WHEN a.co_diamorcro > 60 AND a.co_diamorcro <= 120 THEN '61-120 dpd'
WHEN a.co_diamorcro > 120 then '>120 dpd'
ELSE 'Refinanced and canceled' END ) AS rolls_rate_t_plus_1 -- Rolls rate (paydays) category in month t plus 1 (February)
FROM risk.portfolio_wfcore a
WHERE
pe_produc= (date_trunc('month', a.pe_produc + interval '1 month' - interval '1 day')::date -1) -- Last day of the month
AND to_char(pe_produc,'yyyymm')='201502' -- February month (t+1)
)
;
--- Consolidating data from month t with month t plus one from the temporary table created previously
SELECT
a.product -- Company products
,to_char(a.pe_produc,'yyyymm') AS codmonth --Month of production
,(CASE
WHEN a.co_diamorcro <= 0 THEN '0 dpd'
WHEN a.co_diamorcro > 0 AND a.co_diamorcro <= 8 THEN '1-8 dpd'
WHEN a.co_diamorcro > 8 AND a.co_diamorcro <= 30 THEN '9-30 dpd'
WHEN a.co_diamorcro > 30 AND a.co_diamorcro <= 60 THEN '31-60 dpd'
WHEN a.co_diamorcro > 60 AND a.co_diamorcro <= 120 THEN '61-120 dpd'
WHEN a.co_diamorcro > 120 then '>120 dpd'
ELSE 'Refinanced and canceled' END ) AS rolls_rate_t --Rolls rate(paydays) category in month t (January)
,(CASE
WHEN b.rolls_rate_axes_t_mas_1 IS null THEN 'Refinanced and canceled'
ELSE b.rolls_rate_axes_t_mas_1 END) AS rolls_rate_t_plus_1 --Rolls rate category in month t plus 1 (February)
,COUNT(a.co_contra) AS nro_credit -- nro of credits of month t (January)
,SUM(a.im_salact) AS amount_credit -- amount of credits of month t (January)
FROM risk.portfolio_wfcore a
LEFT JOIN
rolls_rate_t_plus_1 b
ON a.co_contra = b.co_contra
WHERE
a.pe_produc= (date_trunc('month', a.pe_produc + interval '1 month' - interval '1 day')::date -1) -- Last day of the month
AND to_char(a.pe_produc,'yyyymm')='201501' -- January month (t)
GROUP BY 1,2,3,4,5,6
ORDER BY 1,2
Results:
Product | codmonth | rolls_rate_axes_t | rolls_rate_t_plus_1 | nro_credit_t | amount_credit_t |
---|---|---|---|---|---|
Micro | 201501 | 31-60 dpd | 61-90 dpd | 2 | 247.59 |
Micro | 201501 | 61-90 dpd | Refinanced and canceled | 3 | 2388.56 |
Micro | 201501 | 61-90 dpd | 31-60 dpd | 26 | 54251.75 |