简体   繁体   中英

Summarizing consecutive values in T-SQL

I have a question regarding 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. The later is a binary one: 0 if given client has no overdue payment and 1 if he/she has. The question : I would like to create a summary of overdue months (see image 2).

在此处输入图片说明

If its the first month the client is overdue then it should be 1, if second then 2 and so on. 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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