我有一个体育统计数据库。在其中一张表中,我有每个玩家的逐项游戏统计信息。
PK, PlayerID, OpponentID, GameID, Points, Rebounds, etc...
我想知道如何返回查询,例如大多数连续得分至少为20的连续游戏或连续得分为10的连续游戏,等等...(我也有很多其他适用于此的表格,仅以此为例。)
GameID按时间顺序排列,因此这将是确定连续游戏的方式。
[我认为这涉及CTE,但我对此并不精通。
您正在寻找能够实现针对缺口和孤岛问题的解决方案的查询。
您的问题很笼统,所以让我给您一个这样的查询示例,例如:找到连续得分最高20分以上的玩家;还可以找出该系列的第一个和最后一个游戏,以及最高/最低点。
这里是为此目的的查询:
select top 1 with ties
PlayerID,
min(GameID) first_game,
max(GameID) last_game,
min(Points) min_points,
max(Points) max_points,
count(*) consecutive_games
from (
select
s.*,
row_number() over(partition by PlayerID order by GameID) rn,
sum(case when Points >= 20 then 1 else 0 end) over(partition by PlayerID order by GameID) sm
from PlayerStats s
) x
where Points >= 20
group by PlayerID, rn - sm
order by consecutive_games desc;
[这是通过按游戏排序的条件和来进行的,每个游戏的条件总和都超过20分,并将其与游戏序列进行比较。当总和与游戏序列之间的差发生变化时,将开始一组新的游戏;其余只是聚合。您可以独立运行子查询以查看返回的内容。您还可以删除top 1
子句以查看+20点游戏系列的完整列表)。
使用此示例数据:
玩家ID | GameID |点数-------:| -----:| -----:1 | 1 | 101 | 2 | 251 | 3 | 241 | 4 | 321 | 5 | 21 | 6 | 271 | 7 | 421 | 8 | 321 | 9 | 211 | 10 | 20
查询返回:
玩家ID | first_game | last_game | min_points | max_points |连续游戏-------:| ---------:| --------:| ---------:| ---------:| ----------------:1 | 6 | 10 | 20 | 42 | 5
您应该能够对其他统计数据应用相同的逻辑。