簡體   English   中英

計算連續出現次數 SQL - Redshift

[英]Count consecutive ocurrences SQL - Redshift

重新發布,因為某些 postgres 函數在 Amazon Redshift 上不可用。

我正在計算一名員工連續上班的周數。 所以我有這張表,上面有喬恩或安迪是否在某些周上班(我一年中的整個星期都有)。

我正在嘗試使用 Redshift

輸入表

輸入表

我想知道每個人連續工作的次數 x 周數。

所以下面的閱讀方式是安迪連續兩周去了兩次。

Output表

輸出表

謝謝!

我沒有機會在 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.

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