Postgresql 在postgres中求序列的长度

Postgresql 在postgres中求序列的长度,postgresql,window-functions,Postgresql,Window Functions,对博士后来说,这是一个棘手的问题。想象一下,我有一组行,其中包含一个名为(例如)success的布尔列。像这样: id | success 9 | false 8 | false 7 | true 6 | true 5 | true 4 | false 3 | false 2 | true 1 | false 您对这种查询有什么想法吗?您可以使用窗口函数行号()指定序列: select max(id) as max_id, success,

对博士后来说,这是一个棘手的问题。想象一下,我有一组行,其中包含一个名为(例如)success的布尔列。像这样:

id | success 9 | false 8 | false 7 | true 6 | true 5 | true 4 | false 3 | false 2 | true 1 | false
您对这种查询有什么想法吗?

您可以使用窗口函数
行号()
指定序列:

select max(id) as max_id, success, count(*) as length
from (
    select *, row_number() over wa - row_number() over wp as grp
    from my_table
    window
        wp as (partition by success order by id desc),
        wa as (order by id desc)
    ) s
group by success, grp
order by 1 desc

 max_id | success | length 
--------+---------+--------
      9 | f       |      2
      7 | t       |      3
      4 | f       |      2
      2 | t       |      1
      1 | f       |      1
(5 rows)

即使Klin的回答完全正确,我还是想发布我朋友建议的另一个解决方案:

with last_success as (
  select max(id) id from my_table where success
)
select count(mt.id) last_fails_count
from my_table mt, last_success lt
where mt.id > lt.id;

--------------------
| last_fails_count |
--------------------
| 2                |
--------------------


如果我只需要获得最后一个失败或成功的系列,速度会快两倍。

这被称为
间隙和孤岛。
select max(id) as max_id, success, count(*) as length
from (
    select *, row_number() over wa - row_number() over wp as grp
    from my_table
    window
        wp as (partition by success order by id desc),
        wa as (order by id desc)
    ) s
group by success, grp
order by 1 desc

 max_id | success | length 
--------+---------+--------
      9 | f       |      2
      7 | t       |      3
      4 | f       |      2
      2 | t       |      1
      1 | f       |      1
(5 rows)
with last_success as (
  select max(id) id from my_table where success
)
select count(mt.id) last_fails_count
from my_table mt, last_success lt
where mt.id > lt.id;

--------------------
| last_fails_count |
--------------------
| 2                |
--------------------