B
B
bitwheeze2022-01-31 23:45:03
PostgreSQL
bitwheeze, 2022-01-31 23:45:03

How to find the longest sequence of values?

There are three columns in the table: User, Event, Time, where Event is two possible values, for example "A" or "B". Records are sorted by the Time field. How to find the longest chain of value in the Event field?
For example, Vasya has the longest chain, three B events in a row. Petya also has three Bs in the data series, but there was an A event between them, and therefore his longest chain consists of two B events.

Вася	А
Петя	Б
Вася	Б
Женя	А       
Петя	Б
Вася	Б
Женя	А       
Петя	А
Петя	Б
Вася	Б

Result: Vasya, B, 3

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Rozhnev, 2022-02-01
@bitwheeze

Not trivial enough:

with s as (
  select 
 	* ,
 	row_number() over (partition by name order by event_time asc) - 
 	row_number() over (partition by name, event order by event_time asc) gr
  from t
) select 
  name, event, count(*) 
  from s
  group by name, event, gr
  order by count desc
  limit 1;

PostgreSQL fiddle

N
Nikolay Savelyev, 2022-02-01
@AgentSmith

yes, it is possible.
See window functions, just for this task
https://postgrespro.ru/docs/postgrespro/9.5/tutori...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question