簡體   English   中英

對連續整數求和和分組

[英]Sum and group consecutive integers

我需要通過spoken_correctly > 0 對連續整數進行求和和分組。

我可以通過查看laglead找出哪些部分是連續的,但是我不確定如何對連續組的consecutive字段值求和。

即,我有兩組,其中有連續的spoken_correctly值 > 0。綠色的第一組有三行非零spoken_correctly ,綠色的第二組有兩個。

在此處輸入圖片說明

期望的輸出:

在此處輸入圖片說明

此 SQL 生成輸出上方的第一張圖像:

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

這是一個間隙和島嶼問題,可以通過使用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;

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM