我必须创建一个名为“付款状态”字段的报表。本质上,该字段基于客户过去4个月的付款方式。例如,如果他/她每月支付,则该字段评估为“重复”。如果他/她已经在第1个月,第2个月,第3个月但未在第4个月付款,那么答案是“脱落”,依此类推。
我的所有付款数据如下:
Customer ID | Month_Yr | Pymnt_Dt | Pymnt_Amnt 34566 Mar15 | 12 Mar 2015 | 1260 34566 Mar15 | 19 Mar 2015 | 1450 34566 Apr15 | 12 Apr 2015 | 1300 34566 May15 | 12 May 2015 | 1200 34566 May15 | 19 May 2015 | 145 34566 Jun15 | 08 June 2015 | 150 34566 Jun15 | 25 June 2015 | 1900 34567 May15 | 03 May 2015 | 2560 34567 May15 | 16 May 2015 | 1500 34567 May15 | 22 May 2015 | 190 34567 Jun15 | 02 June 2015 | 1456 34567 Jun15 | 20 June 2015 | 1300
如何确定要输入的状态?我可以按客户ID和Month_Yr进行分组,并为每个客户获得每月Month_Yr的总计。但在客户分组方面,我该如何确定状态?
答案 0 :(得分:0)
这不是很干净"但是应该返回一些你可以使用的东西。
DECLARE @Months_to_Fall_Off INT = 4;
SELECT
Customer_ID,
case [Payment Status]
when @Months_to_Fall_Off then 'Recurring'
else 'Fall Off'
end [Payment Status]
FROM (
select
Customer_ID,
ROW_NUMBER() OVER (
PARTITION BY
Customer_ID
ORDER BY
Pymnt_Dt DESC
) [Payment Status],
ROW_NUMBER() OVER (
PARTITION BY
Customer_ID
ORDER BY
Pymnt_Dt
) lastPay
from (
SELECT
Customer_ID,
Month_Yr,
MAX(Pymnt_Dt)Pymnt_Dt,
SUM(Pymnt_Amnt)Pymnt_Amnt
FROM Pymnt_table p
WHERE
Pymnt_Dt >= DATEADD(MONTH,-@Months_to_Fall_Off,GETDATE())
GROUP BY
Customer_ID,
Month_Yr
) t
) t
where
lastPay = 1