Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - select count of repeated continuous sequences

Tags:

sql

postgresql

I have the following table/data:

| 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         |

Is there a way in postgresql to count repeated continuous 'fly' occurrences? In this example, the results should be:

counts
------
  1  
  3
  1
  2
like image 420
Alexey Sviridov Avatar asked Dec 09 '15 16:12

Alexey Sviridov


People also ask

What is Nextval in Postgres?

Function. Description. nextval ( regclass ) → bigint. Advances the sequence object to its next value and returns that value. This is done atomically: even if multiple sessions execute nextval concurrently, each will safely receive a distinct sequence value.

How fast is count Postgres?

By default, count query counts everything, including duplicates. Let's touch upon distinct , which is often used alongside count. This command uses an index-only scan but still takes around 3.5 seconds. The speed depends on many factors, including cardinality, size of the table, and whether the index is cached.


1 Answers

Yes, it's possible, using the lag window function and a cumulative sum:

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

like image 143
sstan Avatar answered Oct 13 '22 00:10

sstan