【问题标题】:How to calculate overall times when consecutive rows appear in PostgreSQL如何计算 PostgreSQL 中出现连续行的总时间
【发布时间】:2020-06-08 20:10:48
【问题描述】:

所以我有一个看起来像这样的表:

id    value    ts
123     T      ts1
123     T      ts2
123     F      ts3
123     T      ts4
456     F      ts5
456     T      ts6
456     T      ts7
456     F      ts8
......

我要做的是计算每个 id 分区下出现连续“T”的次数(每个 id 分区应按列 ts 排序)。但不仅如此,我还想知道连续两个“T”出现了多少次;三个“T”出现了多少次...

所以最后,我想要一个有两列的表:

  1. num_of_consecutives

  2. times_of_occurrences_for_this_number_of_consecutives

在这种情况下,2 个连续的 'T' 出现一次,并且 1 个连续的 T 出现一次,用于 id 123; id 456 出现了 2 个连续的“T”。因此,总结它们,决赛桌应如下所示:

num_of_consecutives    times_of_occurrences_for_this_number_of_consecutives
1                      1
2                      2

【问题讨论】:

  • 行是如何排序的?是否有另一列定义顺序?
  • @Jeremy 是的,有一个专栏叫ts。我已经修改了问题

标签: sql postgresql


【解决方案1】:

请查看此解决方案 (fiddle):

with cte(id, value, ts) as (
select 123,  'T' , 'ts1'
union all
select 123,  'T' , 'ts2'
union all
select 123,  'F' , 'ts3'
union all
select 123,  'T' , 'ts4'
union all
select 456,  'F' , 'ts5'
union all
select 456,  'T' , 'ts6'
union all
select 456,  'T' , 'ts7'
union all
select 456,  'F' , 'ts8'
)
select cnt as num_of_consecutives, count(cnt) as times_of_occurrences_for_this_number_of_consecutives from(
    select value, count(*) cnt from(
       select *,row_number() over (order by ts) - row_number() over (partition by value order by ts) grp
       from cte)q
    group by grp, value 
)q1
where value = 'T'
group by value, cnt
order by cnt;

这个discussion 也很有用。

【讨论】:

  • 非常适合我。谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多