Question

I am not 100% sure how to phrase this question. I searched through the archives as much as I could but could not find what I was looking for.

I have three database tables.

tblSeason(Id,Season)

tblPlayers(ID,FirstName,LastName,DisplayName,Handicap,Current)

tblMatch(ID,MatchDate,Season,Player1,Player2,Player1Score,Player2Score,Winner)

I have been trying to work out how to return something like the following.

Player1

Player2 -- 2 Games Against

Player3 -- 1 Game Against

Player2

Player1 -- 2 Games Against

Player3 -- 3 Games Against

Thanks

SELECT p4.displayname AS [Opponent], count(*) AS [Games Against] 
FROM ((SELECT player1,player2 FROM tblMatch) 
UNION ALL SELECT player2, player1 FROM tblMatch) m 
INNER JOIN tblPlayers p4 ON m.Player2=p4.id) 
WHERE player1=(SELECT p3.id FROM tblPlayers p3 WHERE p3.displayname=?) 
GROUP BY player1, player2;

I am using Visual Studio and inserting parameter to perform this query for 1 player at a time.

The following is working without showing names of players.

SELECT m.Player2 AS [Opponent], count(*) AS [Games Against] 
FROM (SELECT player1,player2 FROM tblMatch
UNION ALL SELECT player2, player1 FROM tblMatch) m 
WHERE player1=1 
GROUP BY player2;

Thanks for your help pointing me in the right direction. I ended up getting the result I wanted using the following.

SELECT p4.displayname AS [Opponent], count(*) AS [Games Against]
FROM ((SELECT player1, player2
FROM(tblMatch)
UNION ALL
SELECT player2, player1
FROM tblMatch) m
INNER JOIN tblPlayers p4 ON m.Player2=p4.id)
WHERE player1=1
GROUP BY p4.displayname;
Was it helpful?

Solution

The basic form of your query is:

select player1, player2, count(*)
from tblMatch m
group by player1, player2;

However, you actually want the game reported both ways. For this, you can use union all:

select player1, player2, count(*)
from (select player1, player2
      from tblMatch
      union all
      select player2, player1
      from tblMatch
     ) m
group by player1, player2;

If you want additional information about the players (such as their names), then you need to join in additional tables.

OTHER TIPS

You can use group by in your query.

SELECT id, player, match
FROM tables
GROUP BY id, player, match
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top