Search code examples
sqlsql-serversql-server-2014-express

Count and Sum consecutive records with minimum value


I have a table that shows payments for clients summarized by months. It looks like this:

Client | Month1 | Month2 | Month3 | Month4 | Month5 | Month6  
------------------------------------------------------------
x1     | 100    | 200    | NULL   | 100    | 100    | 100  
x2     | 100    | 200    | NULL   | NULL   | 100    | 100  
x3     | NULL   | NULL   | 200    | 100    | 100    | 100  
x4     | NULL   | 200    | 300    | 100    | 100    | NULL  
x5     | 100    | 200    | 200    | 100    | 100    | 100  
x6     | NULL   | NULL   | NULL   | 100    | 100    | 100  
x7     | NULL   | 200    | 300    | 100    | 100    | 100  
x8     | NULL   | 200    | NULL   | 100    | 100    | NULL  

I need to summarize the values of consecutive payments where the number of consecutive is >=3 and the interval is calculated backwards from the last month.

So all who have Months 6, 5 and 4 should be summarized as well as the ones which consecutive payments extend more into the past. With this in mind, and from the above example, clients 1, 3, 5, 6 and 7 should be in and for them, sum's should be:

X1 - Last 3 months  
X3 - Last 4 months  
X5 - Last 6 months  
X6 - Last 3 Months  
X7 - Last 5 months

So all months from the last one into the past, where consecutive is >=3, until the first break (month with no payment).


Solution

  • A ツ's answer is very, very good, but the apply is totally unnecessary. Just use a subquery or CTE:

    select d.*
    from (select d.*,
                 (case when month6 is null then 0
                       when month5 is null then 1
                       when month4 is null then 2
                       when month3 is null then 3
                       when month2 is null then 4
                       when month1 is null then 5
                  end) as cnt
          from data d
         ) d
    where cnt >= 3;