[英]Count consecutive ocurrences SQL - Redshift
我沒有機會在 Redshift 中嘗試這個查詢,所以我改為在 PostgreSQL 中運行它。 我猜其中的函數足夠通用,可以在 Redshift 中毫無問題地運行。
select person, consecutive_weeks, count(*) as times
from (
select person, g, count(*) as consecutive_weeks
from (
select *,
row_number() over (partition by person order by week) -
sum(went_to_work) over (partition by person order by week) as g
from t
) x
where went_to_work <> 0
group by person, g
) y
group by person, consecutive_weeks
order by person, consecutive_weeks
結果:
person consecutive_weeks times
------- ------------------ -----
andy 2 2
john 2 1
john 3 1
請參閱db<>fiddle中的運行示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.