Island summing with gaps...

Matty 41 Reputation points

Hi Team,

Suppose I have a table that looks as follows:


I want to use the NULLs (blank cells here) as a means of identifying the 'islands' to sum as well as using the last date for each 'island' as the date assigned to the summed value. The output would be as follows:


Hope what I'm trying to do makes sense. I've been playing around with row_number / over / partition by, but can't get the logic quite right.



A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,597 questions
{count} votes

Accepted answer
  1. Viorel 114.5K Reputation points

    Check one of possible solutions:

    with E1 as
        select *, 
            lag([Value]) over (order by [Date]) as [prev],
            lead([Value]) over (order by [Date]) as [next]
        from MyTable
    E2 as
        select *,
            (select max([Date]) from E1 where [prev] is null and [Value] is not null and [Date] <= e.[Date]) sd
        from E1 e
    select [Date],
        (select sum([Value]) from MyTable where [Date] between sd and e.[Date]) [Value]
    from E2 e
    where [Value] is not null and [next] is null
    order by [Date]
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Matty 41 Reputation points

    Thanks Viorel!

    Not used the LAG and LEAD functions before - I will investigate!



    0 comments No comments