查找对战次数最多的球队

cen*_*980 1 sql postgresql aggregate-functions

I have the following table called Involves:

match  |  team
10     |  A
10     |  B
20     |  B
20     |  C
30     |  C
30     |  A
40     |  D
40     |  C
50     |  A
50     |  B
Run Code Online (Sandbox Code Playgroud)

The values in the column 'match' refer to the unique id of the match and the values in the column 'team' refer to the unique id of the team.

I am trying to write a query that will output the pair of teams that have played the most matches against each other. The output show look like the following:

team1  |  team2  |  matches
A      |  B      |  2
Run Code Online (Sandbox Code Playgroud)

Since A and B have played against each other in two matches, matches 10 and 50.

To solve this problem, I am thinking that you would have to find all possible team pair combinations and then find the total number of matches each pair has played against each other. From this result set, you can select the tuples that have the maximum value for the total matches played. However, I am not sure how I can go about writing such a query, especially with regards to finding all pair combinations. Any insights are appreciated.

Sal*_*n A 5

Something like:

SELECT team1
     , team2
     , COUNT(*) AS matches_played
FROM (
    SELECT match
         , MIN(team) AS team1
         , MAX(team) AS team2
    FROM t
    GROUP BY match
) AS x
GROUP BY team1, team2
ORDER BY COUNT(*) DESC
Run Code Online (Sandbox Code Playgroud)

The inner query is used to generate ordered pairs such as (a, b), (a, c) and (b, c).