以下是我需要提取信息的小数据快照。
ID FREQ LTD SD LWD DPD
_______________________________________________________
1021 Weekly 2016-05-27 2016-05-23 2016-05-31 0
1021 Weekly 2016-05-27 2016-05-27 2016-05-31 0
1021 Weekly 2016-06-02 2016-06-06 2016-06-30 24
1021 Weekly 2016-06-02 2016-06-13 2016-06-30 17
1021 Weekly 2016-06-02 2016-06-20 2016-06-30 10
1021 Weekly 2016-06-02 2016-06-27 2016-06-30 0
1021 Weekly 2017-02-27 2017-02-06 2017-02-28 0
1021 Weekly 2017-02-27 2017-02-13 2017-02-28 0
LTD =该月的最后交易日期
SD =付款应该到来的那个月的预定日期。
LWD =该月的最后工作日。
DPD =过去天数,计算方式为
when freq = 'Weekly' and SD between LTD and LWD AND datediff(LWD, SD) > 7 THEN datediff(LWD, SD) as DPD
。所有日期都是日期数据类型。
现在,请参阅示例数据并注意第6行和第7行。第7行将DPD计算为0,同时考虑LWD
和' SD'当月但是,考虑到2016-06-02
下一次付款2017-02-27
之后,应该计算DPD,因此在DPD计算中,应该在未进行交易的未来6个月内添加天数。
我怎样才能做到这一点?任何帮助赞赏。
我目前的查询是:
select y.*,
case when freq_term = 'Daily' and scheduled_date between last_transaction_date and last_working_day
AND datediff(last_working_day, Scheduled_Date) > 1 THEN datediff(last_working_day, Scheduled_Date)
-- WHEN freq_term = 'Daily' AND datediff(last_working_day, Scheduled_Date) > 1 THEN datediff(last_working_day, Scheduled_Date)
-- when freq_term = 'Weekly' and scheduled_date between last_transaction_date and last_working_day
-- AND datediff(last_working_day, Scheduled_Date) > 7 THEN datediff(last_working_day, Scheduled_Date)
WHEN freq_term = 'Weekly' AND datediff(last_working_day, Scheduled_Date) > 7 THEN datediff(last_working_day, Scheduled_Date)
WHEN freq_term = 'Bi-Monthly' AND datediff(last_working_day, Scheduled_Date) > 14 THEN datediff(last_working_day, Scheduled_Date)
WHEN freq_term = 'Monthly' AND datediff(last_working_day, Scheduled_Date) > 30 THEN datediff(last_working_day, Scheduled_Date) END 'DPD'
from
(
select id,
freq_term,
max_date 'Last_Transaction_date',
t3.date 'Scheduled_date',
date(last_day(date) - (CASE DAYOFWEEK(last_day(date)) WHEN 1 THEN 2 WHEN 7 THEN 1 ELSE 0 END)) as 'Last_working_day'
from
(
select
jlp.id,
jlp.freq_term,
t1.max_date,
t1month,
t1year
from jos_lender_portfolio jlp
inner join
(
select lpid, year(date) t1year, month(date) t1month, max(date) max_date
from jos_lender_transactions
where description in('Payment', 'Partial Payoff', 'Early Payoff')
and date <= '2018-01-01'
group by lpid, year(date),month(date)
)t1 on jlp.id = t1.lpid
where id = 1021
order by 3
)t
inner join
(SELECT
lpid,
date,
MONTH(DATE) t3month,
year(date) t3year
from jos_lender_trans_backup where description = 'Payment' and lpid = 1021 order by date
)t3
on t.id = t3.lpid and t.t1month = t3.t3month and t.t1year = t3.t3year
)y
group by id, last_day(Last_Transaction_date)
order by Scheduled_Date;