Skip to content
Advertisement

Recursive query to get totals by distinct item from a row of a data

I have SQL data that looks like the following:

How can I recurse through this data to get total wins, draws, losses by team for both home and away? My output would look something like:

I was able to get this done in a very linear way by simply get a list of distinct teams and for each team looping through the data and tallying the win, draw, loss total and aggregating that into variables. However, I imagine there may be a different way to accomplish this.

Advertisement

Answer

You don’t need recursion here, you can just unpivot the Home and Away sides, then group by the Team and do conditional aggregation

Team Wins Draws Losses
Botswana 0 1 0
DRC 0 1 0
France 1 1 0
USA 0 1 1

db<>fiddle

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