计算SQL Server中连续出现的值的最大数量

时间:2017-09-26 12:38:27

标签: sql sql-server gaps-and-islands

我有一个包含玩家,结果和ID的表格:

Player | Result | ID
---------------
An     | W      | 1
An     | W      | 1
An     | L      | 0
An     | W      | 1
An     | W      | 1
An     | W      | 1
Ph     | L      | 0
Ph     | W      | 1
Ph     | W      | 1
Ph     | L      | 0
Ph     | W      | 1

A' W'将始终具有ID,

我需要创建一个查询,计算每个玩家连续“W”的最大数量:

Player | MaxWinStreak
---------------------
An     | 3    
Ph     | 2

我尝试使用Rows Unbounded Preceeding但我只能计算Ws的最大数量,而不是连续

    Select
    t2.player
    ,max(t2.cumulative_wins) As 'Max'

    From

    (   Select 
            t.Player
            ,Sum(ID) Over (Partition By t.Result,t.player 
             Order By t.GameWeek Rows Unbounded Preceding) As cumulative_wins

        From
             t  

             ) t2

    Group By
    t2.player

我可以采取不同的方法吗?

1 个答案:

答案 0 :(得分:3)

您需要一个列来指定排序。 SQL表表示无序集。在下面的查询中,?代表此列。

您可以使用行数的差异来获得每个连胜纪录:

select player, count(*) as numwins
from (select t.*,
             row_number() over (partition by player order by ?) as seqnum, 
             row_number() over (partition by player, result order by ?) as seqnum_r 
      from t
     ) t
where result = 'W'
group by player, (seqnum - seqnum_r);

然后你可以获得最大值:

select player, max(numwins)
from (select player, count(*) as numwins
      from (select t.*,
                   row_number() over (partition by player order by ?) as seqnum, 
                   row_number() over (partition by player, result order by ?) as seqnum_r 
            from t
           ) t
      where result = 'W'
      group by player, (seqnum - seqnum_r)
     ) pw
group by player;