Skip to content
Advertisement

Oracle create league table from football results

Having the below table

DATE_MATCH HOME_TEAM AWAY_TEAM HOME_GOALS AWAY_GOALS
03-APR-21 Alaves Eibar 2 1
02-APR-21 Alaves Huesca 3 0
01-APR-21 Eibar Huesca 1 1
31-MAR-21 Huesca Eibar 2 0
30-MAR-21 Eibar Alaves 1 1
29-MAR-21 Huesca Alaves 1 0

How to generate the table:

I’d like to get the below one (league table). It would be ideal if it was possible just using pivot and unpivot clauses:

TEAM W D L GOALS_SCORED GOALS_RECEIVED POINTS
Alaves 2 1 1 6 3 7
Huesca 2 1 1 4 4 7
Eibar 0 2 2 3 6 2

Advertisement

Answer

unpivot, process, pivot is how I would do it too. However, I do the “pivoting” the “old way” (conditional aggregation), because you don’t really want to “pivot”. You are counting the wins, draws and losses separately, but the goals scored and goals received are aggregated over all results; that is not “pivoting”. For this kind of mixed aggregation (some is conditional, some is not), the good old group by is a better tool.

Something like this:

Output:

Notice how I rearranged your sample data (the first subquery in the with clause) so that it fits in just a few lines of code. You aren’t paid by the line on this site, so there is no need to do in 60 lines what can be done in 8.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement