If I've understood what you want, you can do this with analytic functions and windowing clauses.
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;
The inner select calculates the number of matches and the total number of goals across them, for each home/away team in each season, using the analytic version of count
and sum
, and the window clause rows between ...
limits both to the previous five, excluding the current row, which I think is what you want. The outer select then adds the relevant totals together for the two teams in the current row, but checks both counts and leaves the total null if either is < 5. Note that it only hits the matches
table once.
With an additional filter immediately before the order-by:
where season = 2012 and homeTeam = 'Norwich' and awayteam = 'Aston Villa'
... you get:
SEASON MATCHDATE HOMETEAM AWAYTEAM HOMEGOALS AWAYGOALS TOTALGOALS
---------- --------- ------------------------- ------------------------- ---------- ---------- ----------
2012 13-MAY-12 Norwich Aston Villa 2 0 30
You could use this to update the table for the matching row, though generally I'd calculate it as needed to avoid potential data integrity errors, possibly in a view.