简体   繁体   中英

Sum and group consecutive integers

I need to sum and group consecutive integers by spoken_correctly > 0.

I'm able to find out which sections are consecutive by looking at lag and lead , but then am not sure how to sum contiguous groups consecutive field's values.

Ie, I have two groups where there are consecutive spoken_correctly values > 0. The first group in green has three rows of non-zero spoken_correctly , the second group in green has two.

在此处输入图片说明

Desired output:

在此处输入图片说明

This SQL produces the first image above output:

select *, case when (q.times_spoken_correctly > 0 and (q.lag > 0 or q.lead > 0)) then 1 else 0 end as consecutive
from (
    select *, lag(q.times_spoken_correctly) over (partition by q.profile_id order by q.profile_id) as lag, lead(q.times_spoken_correctly) over (partition by q.profile_id order by q.profile_id) as lead
    from (
        SELECT *
        FROM ( VALUES (3, 0, '2019-01-15 19:15:06'),
                      (3, 0, '2019-01-15 19:15:07'),
                      (3, 1, '2019-01-15 19:16:06'),
                      (3, 2, '2019-01-15 19:16:10'),
                      (3, 2, '2019-01-15 19:17:06'),
                      (3, 0, '2019-01-15 19:17:11'),
                      (3, 0, '2019-01-15 19:39:06'),
                      (3, 3, '2019-01-15 19:40:10'),
                      (3, 4, '2019-01-15 19:40:45')
             ) AS baz ("profile_id", "times_spoken_correctly", "w_created_at")
    ) as q
) as q

This is a gaps and islands problem, which can be solved by forming groups of sequences using row_number

select profile_id, count(*)  as consec FROM 
(
SELECT t.*, row_number() OVER ( PARTITION BY profile_id  ORDER BY w_created_at ) -
            row_number() OVER ( PARTITION BY profile_id, CASE times_spoken_correctly 
                         WHEN 0 THEN 0 ELSE 1 END 
            ORDER BY w_created_at ) as seq --group zeros and non zeros
            FROM t ORDER BY w_created_at
    ) s WHERE  times_spoken_correctly > 0 --to count only "> zero" groups.
    GROUP BY profile_id,seq;

Demo

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