Finding the largest group of consecutive numbers within a partition

人盡茶涼 提交于 2019-12-04 12:52:12

You can do this with window functions.

select player_id, runs, count(*) as numruns
from (select p.*,
             (row_number() over (partition by player_id order by match_date) -
              row_number() over (partition by player_id, runs order by match_date)
             ) as grp
      from players p
     ) pg
group by grp, player_id, runs
order by numruns desc
limit 1;

The key observation is that "runs in a sequence" have this property: if you enumerate the rows (for each player) by date and you enumerate the rows for each player and by the runs by date, then the difference is constant when the runs are all the same and in order. That forms a group that you can use for aggregation to identify the player you want.

Here is the SQL Fiddle.

select p1.player_id, p1.match_date, p1.runs, count(p2.match_date) from players p1
join players p2 on p1.player_id = p2.player_id
    and p1.match_date >= p2.match_date
    and p1.runs = p2.runs
    and not exists (
        select 1 from players p3
        where p3.runs <> p2.runs
        and p3.player_id = p2.player_id
        and p3.match_date < p1.match_date
        and p3.match_date > p2.match_date
    )
group by p1.player_id, p1.match_date, p1.runs
order by p1.player_id, p1.match_date

http://sqlfiddle.com/#!15/78a77/1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!