question

Island summing with gaps...

Hi Team,

Suppose I have a table that looks as follows:

][2]

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.

Thanks,

Matty

image.png (16.3 KiB)
image.png (3.9 KiB)
· 7

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi Viorel-1,

Can this solution be adapted based on a further column, like this?

Which would mean the following result:

Thanks,

Matty

image.png (32.5 KiB)
image.png (7.7 KiB)
Matty-4135

This seems to work:

`````` ;
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 Product, [Date], (select sum([Value]) from MyTable where [Date] between e.sd and e.[Date]) [Value]
from E2 e
where [Value] is not null and [next] is null
order by [Date]
``````
Viorel-1

Hi again,

Thanks for responding, but that doesn't quite give me what I need.

Here's what it's returning (for me at least):

Green records are correct; orange ones not. The problem appears to be where Products have date ranges that overlap.

Any ideas?

Thanks,

Matty

image.png (10.4 KiB)

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]
``````
·

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.