[英]For each row count how many previous rows fall behind based on the date SQL BigQuery
我在 BigQuery 中有一个带有还款订阅计划的表,如下所示:
ID | 子月号 | to_be_paid_date | 实际付款日期 | 迟到了 |
---|---|---|---|---|
156 | 1 | 2020-03-01 | 2020-03-01 | 不 |
156 | 2 | 2020-04-01 | 2021-06-02 | 是的 |
156 | 3 | 2020-05-01 | 2020-06-07 | 是的 |
156 | 4 | 2020-06-01 | 2021-06-07 | 是的 |
对于每个客户id
,都有订阅月份编号和我们希望他们支付订阅费用的日期。 我知道哪些付款比预期迟到,但我想知道在下一次付款到期时之前的许多个月都没有付款。
例如,到第 4 个月的订阅到期时 (2020-06-01),第 2 个月和第 3 个月仍未付款。 所以我试图计算像这样的东西num_past_overdue
:
ID | 子月号 | to_be_paid_date | 实际付款日期 | num_past_overdue |
---|---|---|---|---|
156 | 1 | 2020-03-01 | 2020-03-01 | - |
156 | 2 | 2020-04-01 | 2021-06-02 | 0 |
156 | 3 | 2020-05-01 | 2020-06-07 | 1 |
156 | 4 | 2020-06-01 | 2021-06-07 | 2 |
我尝试使用 LEAD function 和 CASE WHEN,但它只给我上个月是否已支付的信息,而不是在下个月到期时未支付前几个月的信息。
WITH payments as (
SELECT *
,LEAD(to_be_paid_date) OVER (PARTITION BY id ORDER BY id, to_be_paid_date) AS next_due_date
FROM table)
SELECT *
, CASE WHEN DATE_DIFF(actual_payment_date, next_due_date, DAY)> 0 THEN True
ELSE False END AS overdue_when_next_was_due
FROM payments
试试下面的方法:
with t1 as (
select 156 as id, 1 as sub_month_number, date('2020-03-01') as to_be_paid_date, date('2020-03-01') as actual_payment_date, 'no' as was_late,
union all select 156 as id, 2 as sub_month_number, date('2020-04-01') as to_be_paid_date, date('2021-06-02') as actual_payment_date, 'yes' as was_late,
union all select 156 as id, 3 as sub_month_number, date('2020-05-01') as to_be_paid_date, date('2020-06-07') as actual_payment_date, 'yes' as was_late,
union all select 156 as id, 4 as sub_month_number, date('2020-06-01') as to_be_paid_date, date('2021-06-07') as actual_payment_date, 'yes' as was_late,
)
select
*,
sum(
case
when was_late='yes' then 1
else 0
end
) over(order by actual_payment_date) as num_past_overdue
from t1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.