我需要的是:我必须列出所有有付款计划的客户(我们每个月都会收取费用)并且有这样的组合:第一笔付款已完成,接下来的2付款仍未支付。财务表有:
ID,PAYMENTPLANID,DATEDUE,AMOUNTEDUE,AMOUNTPAID
我知道在AMOUNTPAID>时支付行。 0和DATEDUE表示 我需要,因为如果客户只支付第一笔费用并在接下来的2个月内停止,我将在第3个月末取消付款计划。
有没有更简单的方法来识别这个不涉及3个子选择的人(我想到的唯一方法)?
示例:
+--------------------------------------------------------+
| ID, PAYMENTPLANID, DATEDUE, AMOUNTEDUE, AMOUNTPAID |
+--------------------------------------------------------+
| 1, 1, 2017-07-05, 10, 0 |
| 1, 1, 2017-06-05, 10, 0 |
| 1, 1, 2017-05-05, 10, 10 |
| 2, 5, 2017-07-05, 25, 25 |
| 2, 5, 2017-06-05, 25, 0 |
| 2, 5, 2017-05-05, 25, 25 |
+--------------------------------------------------------+
ID 1的付款计划应该在本月取消,因为该人只支付了第一笔付款。 付款计划5不应取消。
答案 0 :(得分:3)
您可以将lead
与可选的第二个参数一起使用,以查看前面的1行和2行,并检查您的条件。
select * --distinct paymentplanid /*if only planid is needed as output*/
from (
select t.*
,lead(amountpaid,1) over(partition by paymentplanid order by datedue) as nxt_1
,lead(amountpaid,2) over(partition by paymentplanid order by datedue) as nxt_2
,lag(amountpaid) over(partition by paymentplanid order by datedue) as prev_1
from tbl t
) t
where amountpaid>0 and prev_1 is null and nxt_1=0 and nxt_2=0
答案 1 :(得分:0)
这样的事情应该有用吗?
select ID , PaymentplandID from
(select ID , PaymentplandID , max(amount_paid ) over ( order by ID ,
PaymentplandID rows between current row and 1 following partion by Datedue desc )
as amount ,
row_number() over ( order by select ID , PaymentplandID partion by Datedue asc) as rn
from you_tble) t1
where t1.amount = 0 and rn = 3