Search code examples
sqlwindow-functionsverticagaps-and-islands

Grouping rows by value until it changes (grouping includes the first changed value)


I have the following dataset:

enter image description here

The rows are sorted in ascending order by the start_time field, and I want to group rows that have a sequence of false values, until the first true value, including the first true value.

That is, for the above dataset I want the following output:

enter image description here

(the grouping field can include other values than what I wrote)


Solution

  • I think a window sum can do what you want:

    select t.*, 
        1 + coalesce(sum(case when bool = true then 1 else 0 end) over(
                order by start_time
                rows between unbounded preceding and 1 preceding
            ), 0) as grp
    from mytable t