简体   繁体   English

总结 T-SQL 中的连续值

[英]Summarizing consecutive values in T-SQL

I have a question regarding T-SQL:我有一个关于 T-SQL 的问题:

I have a database of my insurance clients, who have a contractual obligation to pay the company insurance fee ever month.我有我的保险客户的数据库,他们有合同义务每月支付公司保险费。 An example of the dataset is presented below:数据集的示例如下所示:

在此处输入图片说明

I have the date and client_id and the overdue_flag.我有日期和 client_id 以及 overdue_flag。 The later is a binary one: 0 if given client has no overdue payment and 1 if he/she has.后者是二进制的:0 如果给定的客户没有逾期付款,则 1 如果他/她有。 The question : I would like to create a summary of overdue months (see image 2).问题:我想创建一个过期月份的摘要(见图 2)。

在此处输入图片说明

If its the first month the client is overdue then it should be 1, if second then 2 and so on.如果是客户逾期的第一个月,则应为 1,如果是第二个月,则为 2,依此类推。 However, if the client comes clean (makes good on overdue payments) it should go back to 0, and if the same client is overdue again, the count of overdue months should restart the count from 1. In other words: I only would like to sum the consecutive overdue months.但是,如果客户干净(使逾期付款顺利)它应该回到 0,如果同一个客户再次逾期,逾期月份的计数应该从 1 重新开始计数。换句话说:我只想要对连续逾期的月份求和。

Thanks in advance for the help!在此先感谢您的帮助!

Use a cumulative sum to define the groups by the number of non-overdue months before each row.使用累积总和按每行之前的非逾期月数定义组。 Then row_number() for the overdue periods:然后为过期期间的row_number()

select t.*,
       (case when overdue_flag = 1
             then row_number() over (partition by client_id, grp, overdue_flag order by date)
        end) as months_overdue
from (select t.*,
             sum(1 - overdue_flag) over (partition by client_id order by date) as grp
      from t
     ) t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM