sql – 查找分区中最大的连续数字组

我有以下数据由player_id和match_date排序.我想找出连续运行次数最多的记录组(连续3次从2014-04-03到2014-04-12 4次运行)

 player_id  match_date  runs
    1       2014-04-01    5
    1       2014-04-02    55       
    1       2014-04-03    4       
    1       2014-04-10    4       
    1       2014-04-12    4       
    1       2014-04-14    3       
    1       2014-04-19    4       
    1       2014-04-20    44               
    2       2014-04-01    23
    2       2014-04-02    23       
    2       2014-04-03    23       
    2       2014-04-10    23       
    2       2014-04-12    4       
    2       2014-04-14    3       
    2       2014-04-19    23       
    2       2014-04-20    1   

我想出了以下SQL:

select *,row_number() over (partition by ranked.player_id,ranked.runs
order by ranked.match_date) as R from (
select player_id ,match_date,runs from players order by 1,2 desc )
ranked order by ranked.player_id, match_date asc

但这继续从之前的连续运行中排名(2014-04-19的4次运行,预计玩家1将获得排名1,但由于已经发生了3次同一分区,因此获得了排名4).类似地,2014-04-19的玩家2的23次运行预计将获得等级1,但是因为此玩家已经有4次出现23次运行,所以获得等级5.

当运行值从上一行更改时,如何将等级重置为1?

架构,数据,SQL和输出在SQLFiddle上可用.

最佳答案 您可以使用窗口功能执行此操作.

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;

关键的观察是“按顺序运行”具有以下属性:如果按日期枚举行(对于每个玩家)并且您枚举每个玩家的行和按日期运行,则运行时差异是恒定的是完全相同的.这形成了一个可用于聚合的组,以识别您想要的玩家.

Here是SQL小提琴.

点赞