-2

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;
Jono Hill
  • 3
  • 2

2 Answers2

0

You can use group by in your query.

SELECT id, player, match
FROM tables
GROUP BY id, player, match
ama
  • 55
  • 1
  • 10
0

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Thanks, this works exactly how I need. Although I am having trouble understanding where to join to get the player2 information from player table. I have tried the following. – Jono Hill Aug 25 '13 at 03:59
  • See original post for additional details.. Thanks – Jono Hill Aug 25 '13 at 04:08