gpt4 book ai didi

sql - 计算 SQL Server 中一个值的最大连续出现次数

转载 作者:行者123 更新时间:2023-12-05 01:44:22 24 4
gpt4 key购买 nike

我有一张包含球员、结果和 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

“W”的 ID 始终为 1,

我需要创建一个查询来计算每个玩家连续“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

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

最佳答案

您需要一个列来指定排序。 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;

关于sql - 计算 SQL Server 中一个值的最大连续出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46426820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com