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

时间:2015-12-09 16:50:08

标签: sql 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

1 个答案:

答案 0 :(得分:3)

是的,可以使用lag窗口函数和累积总和:

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,
         t.data,
         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