I have two postgresql tables with the following data
[teams]
[id][team_name]
1 team 1
2 team 2
3 team 3
[matches]
[participant 1][participant 2]
1 3
2 1
3 2
The matches table references the team ID.
I am trying to count the number of times each team has played a match, so that it is possible to display the total number of games each team has played. I have unsuccessfully attempted to do this for hours with UNIONS, COUNT etc. Would appreciate any assistance to tackle this.
2
Answers
As you can see, each record within
matches
is actually two records:participant 1
has a home match (let it be
kind = 1
) whileparticipant 2
has a guest match (kind = 2
).So far so good, let’s duplicate each record (with a help of
cte
) and then we can use good oldcount
andgroup by
I would go with the following solution:
The COUNT() function is used to count the number of unique team names. The DISTINCT keyword ensures that only unique values are counted by the COUNT() function. The UNION operator is used to combine the team names from different sources – directly from the teams table and via joins with the matches table.