微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL – 选择重复连续序列的计数

我有以下表/数据:

| user_id | action_id | data        |
------------------------------------- 
| 10      |    1      | fly         |
| 10      |    2      | train       |
| 10      |    3      | fly         |
| 10      |    4      | fly         |
| 10      |    5      | fly         |
| 10      |    6      | train       |
| 10      |    7      | fly         |
| 10      |    8      | train       |
| 10      |    9      | fly         |
| 10      |   10      | fly         |

在postgresql中有没有办法计算重复的连续“飞行”事件?在此示例中,结果应为:

counts
------
  1  
  3
  1
  2

解决方法

是的,可以使用滞后窗函数和累积和:

with FlagCTE as (
  select t.action_id,t.data,case when t.data = 'fly' and t.data = lag(t.data) over (order by t.action_id) then 0 else 1 end as Flag
    from some_table t),GroupCTE as (
  select t.action_id,sum(t.Flag) over (order by t.action_id) as GroupId
    from FlagCTE t
   where t.data = 'fly')
select count(*) as counts
  from GroupCTE t
 group by t.GroupId
 order by t.GroupId

SQLFiddle Demo

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐