【问题标题】:Finding consecutive patterns (with SQL)查找连续模式(使用 SQL)
【发布时间】:2018-04-18 17:39:51
【问题描述】:

PostgreSQL 中的表consecutive: 每个se_id 都有一个idx 从 0 到 100 - 这里是 0 到 9。

搜索模式:

SELECT *
FROM consecutive
WHERE val_3_bool = 1
AND val_1_dur > 4100 AND val_1_dur < 5900

现在我正在寻找这种模式的最长连续出现时间 对于每个p_id - 和计数val_1_durAVG

可以用纯 SQL 计算吗?

table as txt "Result" as txt

【问题讨论】:

标签: sql postgresql gaps-and-islands


【解决方案1】:

一种方法是行号的差异方法来获取每个序列:

select pid, count(*) as in_a_row, sum(val1_dur) as dur
from (select t.*,
             row_number() over (partition by pid order by idx) as seqnum,
             row_number() over (partition by pid, val3_bool order by idx) as seqnum_d
      from consecutive t
     ) t
group by (seqnun - seqnum_d), pid, val3_bool;

如果您专门寻找“1”值,则将where val3_bool = 1 添加到外部查询中。为了理解为什么会这样,我建议你盯着子查询的结果,这样你就可以理解为什么差异定义了连续的值。

然后您可以使用distinct on 获得最大值:

select distinct on (pid) t.*
from (select pid, count(*) as in_a_row, sum(val1_dur) as dur
      from (select t.*,
                   row_number() over (partition by pid order by idx) as seqnum,
                   row_number() over (partition by pid, val3_bool order by idx) as seqnum_d
            from consecutive t
           ) t
      group by (seqnun - seqnum_d), pid, val3_bool;
     ) t
order by pid, in_a_row desc;

distinct on 不需要额外的子查询级别,但我认为这使逻辑更清晰。

【讨论】:

  • 听起来很有趣。 ;) 但我只寻找特定模式的连续匹配。
  • @Teletubbi-OSX 。 . .这可以满足您的需求。只需将where 子句添加到group by 之前的查询中,如答案中所述。
  • 是的,它有效!谢谢。但是这个过程有点慢。大约需要 30 秒。 (表大小 750MB)。
【解决方案2】:
猜你喜欢
  • 2021-11-10
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多