将每一行与条件关联到最新的前一行的有效方法。(PostgreSQL)

Efficient way to associate each row to latest previous row with condition.(PostgreSQL)

我有一个 table,其中插入了两种不同类型的行:

在实际问题中,我有一个时间戳列,用于存储事件的顺序。在 SQL Fiddle 示例中,我使用了一个 SERIAL 整数字段,但它是相同的想法。

示例如下:

http://www.sqlfiddle.com/#!17/a0823/6

我正在寻找一种 高效 方法来检索第一种类型的每一行及其状态(由当前行之前的最新状态行给出)关联。

sqlfiddle link上的查询是一个例子,但是使用了两个非常低效的子查询。

我无法更改 table 的结构,也无法创建其他 table,但我可以在 table.

上创建任何必要的索引

我正在使用 PostgreSQL 11.4

最有效的方法可能是使用window函数:

select p.*
from (select p.*,
             max(attrvalue) filter (where attrname = 'status_t1') over (partition by grp_1 order by id) as status_t1,
             max(attrvalue) filter (where attrname = 'status_t2') over (partition by grp_2 order by id) as status_t2
      from (select p.*,
                   count(*) filter (where attrname = 'status_t1') over (order by id) as grp_1,
                   count(*) filter (where attrname = 'status_t2') over (order by id) as grp_2
            from people p
           ) p
     ) p
where attrname not in ('status_t1', 'status_t2');

Here 是一个 db<>fiddle.