Skip to content
Advertisement

SQL – Aggregate all EXCEPT group

Consider the following sample table from a soccer tournament (let’s call this table matches)

The resulting table we want should give us each club’s total goals scored AND goals conceded:

Getting goals scored is straight forward enough…

but I am absolutely flummoxed as to how to get it for each team’s opponents.

I could, of course, construct a pretty complex array of subqueries to get there. If this were application-side work I’d likely just stuff it in a loop and iterate over each club to get there, but my use case requires a SQL answer if possible. Any thoughts?

edit: also if anyone has any better ideas on how to title this question, I’m all ears – I’m not really sure exactly how to describe this problem in the first place.

Advertisement

Answer

We can use a self-join approach here:

This approach brings the goals conceded by each club to the other club, for each match, into a single row. We then just aggregate by club to get the two sums.

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