我正在嘗試計算員工連續上班的周數。所以我有這張表,上面有 jon 或 andy 是否在某些星期上班(我一年中的所有星期都有)。
我正在嘗試使用 Postgresql

我想知道每個人連續作業的次數 x 周數。
所以下面的閱讀方式是安迪連續兩周去了兩次。

我覺得我很親近。在 python 上我可能會使用 for 回圈,但在 Postgresql 上我有點迷茫。
謝謝!
uj5u.com熱心網友回復:
我們將每個人連續作業的周數分組,然后按結果和人分組。
select person
,consecutive_weeks
,count(*)/consecutive_weeks as times
from (
select person
,sum(case when "went to work?" = 1 then 1 end) over(partition by person, grp) as consecutive_weeks
from (
select *
,count(mrk) over(partition by person order by week) as grp
from (
select *
,case when "went to work?" <> lag("went to work?") over(partition by person order by week) then 1 end as mrk
from t
) t
) t
) t
where consecutive_weeks is not null
group by person, consecutive_weeks
order by person
| 人 | 連續_周 | 次 |
|---|---|---|
| 安迪 | 2 | 2 |
| 約翰 | 3 | 1 |
| 約翰 | 2 | 1 |
小提琴
uj5u.com熱心網友回復:
您可以找到一個人在場的幾周id組,為該組的每一行分配一次跑步,然后在結果上應用 a ,在上count執行 a :group byid
with cte as (
select t3.person, t3.k, count(*) c from
(select t.*, (select sum((t1.person = t.person and t1.week <= t.week and t1.at_work = 0)::int) k from tbl t1)
from tbl t) t3
where t3.at_work != 0 group by t3.person, t3.k
)
select c.person, c.c, count(*) c1 from cte c group by c.person, c.c order by c1
見小提琴。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/511355.html
上一篇:API中的分頁和串列
