如果我了解您想要什么,您可以使用分析函数和窗口子句来做到这一点。
select season, matchdate, hometeam, awayteam, homegoals, awaygoals,
case when home_cnt >= 5 and away_cnt >= 5 then
home_tot + away_tot
else null end as totalgoals
from (
select season, matchdate, hometeam, awayteam, homegoals, awaygoals,
count(*) over (partition by season, hometeam
order by matchdate
rows between 5 preceding and 1 preceding) as home_cnt,
sum(homegoals + awaygoals) over (partition by season, hometeam
order by matchdate
rows between 5 preceding and 1 preceding) as home_tot,
count(*) over (partition by season, awayteam
order by matchdate
rows between 5 preceding and 1 preceding) as away_cnt,
sum(homegoals + awaygoals) over (partition by season, awayteam
order by matchdate
rows between 5 preceding and 1 preceding) as away_tot
from matches
)
order by season, matchdate, hometeam, awayteam;
内部选择使用 和 的解析版本计算每个赛季中每个主队/客队的比赛次数和总进球数count
,sum
并且窗口子句rows between ...
将两者限制为前五个,不包括当前行,我认为这就是你想要的。然后,外部选择将当前行中两个团队的相关总数相加,但会检查两个计数,如果其中一个小于 5,则将总数留空。请注意,它只命中matches
表一次。
在 order-by 之前有一个额外的过滤器:
where season = 2012 and homeTeam = 'Norwich' and awayteam = 'Aston Villa'
... 你得到:
SEASON MATCHDATE HOMETEAM AWAYTEAM HOMEGOALS AWAYGOALS TOTALGOALS
---------- --------- ------------------------- ------------------------- ---------- ---------- ----------
2012 13-MAY-12 Norwich Aston Villa 2 0 30
您可以使用它来更新匹配行的表,但通常我会根据需要计算它以避免潜在的数据完整性错误,可能在视图中。