如何根据PostgreSQL中另一列的值计算一列中具有相同值的三个连续记录?

Abd*_*ani 4 postgresql

我有一个表出席如下:

create table attendance (id int, name varchar(30), status varchar(10), date date)  
Run Code Online (Sandbox Code Playgroud)

该表有以下记录:

insert into attendance values (1,'John','absent','2016-03-01');
insert into attendance values (1,'John','absent','2016-03-02');
insert into attendance values (1,'John','absent','2016-03-03');
insert into attendance values (2,'Sam','present','2016-03-04');
insert into attendance values (3,'Sam','absent','2016-03-05');
insert into attendance values (1,'John','absent','2016-03-06');
insert into attendance values (1,'John','absent','2016-03-07');
insert into attendance values (1,'John','absent','2016-03-08');
insert into attendance values (1,'John','present','2016-03-09');
insert into attendance values (1,'John','absent','2016-03-10');
insert into attendance values (1,'John','absent','2016-03-11');
insert into attendance values (1,'John','present','2016-03-12'); 
insert into attendance values (1,'John','absent','2016-03-13');   
Run Code Online (Sandbox Code Playgroud)

现在我要计算一个人连续三个缺席记录的次数。
结果应如下所示:

id name count
 1  John   2  
Run Code Online (Sandbox Code Playgroud)

因为约翰连续三天缺席两次。

如果他们连续 6 天缺席 6 次,则应计为 2,即 (3+3)。

这应该算1连续3日连续3个缺席,即如果约翰不存在的1,2和3月3日,它应该算作1,但如果约翰不存在的1,2和3月4日,然后它不应该算1
4或缺席5次计为1次。

如果没有日期条目,则将其视为“当前”。

任何帮助表示赞赏。

小智 5

另一种解决方案。递归部分创建状态“不存在”的行组。该解决方案使用递归 CTE窗口函数

WITH RECURSIVE a(id, name, date, n)  as (
    SELECT id, name, q.date, 1 as n
    FROM (
        SELECT id, name, date,
            date-lag(date) OVER (PARTITION BY name ORDER BY date) as lag
        FROM  attendance
        WHERE status='absent'
    ) q
    WHERE lag >1 or lag is null
    UNION
    SELECT a.id, a.name, a.date, a.n + 1
    FROM a
    JOIN attendance at ON (
           a.id = at.id and at.name = a.name and at.date = a.date + n)
    WHERE at.status='absent'
)
SELECT id, name, sum(long_absences) FROM (
    SELECT id, name, count(*)/3 as long_absences
    FROM a
    GROUP BY id, name, date having count(*) >=3
    ) as absences
GROUP BY id, name;
Run Code Online (Sandbox Code Playgroud)