Grouping and Joining a Unioned Table. Having Problems

只愿长相守 提交于 2019-12-12 00:39:02

问题


The other day I asked a question and received some very helpful information which assisted me to get this far. However I am now having trouble with taking data from tables using UNION/GROUP BY.

The following code is what I have tried. But I cannot seem to find a way to make it group by Player.

It is showing like this.

Jono - 3 - 1
Jono - 1 - 1

When I need to show like this

Jono - 4 - 1 

I am just beginning so if there is a better way to perform this code, please tell me :)

SELECT [Player],[Played],[Games Won] FROM
(SELECT
p1.displayname AS [Player],
COUNT(p1.displayname) AS [Played],
SUM(IIF(m.player2=m.winner, 1, 0)) AS [Games Won]
FROM ((tblMatch m)
INNER JOIN tblPlayers p1 ON m.player2=p1.id)
WHERE m.season = 3
GROUP BY p1.displayname
UNION ALL
SELECT
p2.displayname AS [Player2],
COUNT(p2.displayname) AS [Played],
SUM(IIF(m.player1=m.winner, 1, 0)) AS [Games Won]
FROM ((tblMatch m)
INNER JOIN tblPlayers p2 ON m.player1=p2.id)
WHERE m.season = 3
GROUP BY p2.displayname)

My Database layout is:

tblPlayers (ID,FirstName,LastName,DisplayName,Handicap,Current)  
tblSeason  (ID,Season)  
tblMatch   (ID,MatchDate,Season,Player1,Player2,Player1Score,Player2Score,Winner)  

And what I would really like to do is show a list where the players name can come from either Player1 or Player2 column and Count the number of games played by this player and From these games Count the number of times they won the game.

Thanks


回答1:


Wouldn't you just put another group by in your outer query:

SELECT [InnerQueryAlias].[Player], Sum([InnerQueryAlias].[Played]) AS SumOfPlayed, Sum([InnerQueryAlias].[Games Won]) AS [SumOfGames Won]
FROM (SELECT
p1.displayname AS [Player],
COUNT(p1.displayname) AS [Played],
SUM(IIF(m.player2=m.winner, 1, 0)) AS [Games Won]
FROM ((tblMatch m)
INNER JOIN tblPlayers p1 ON m.player2=p1.id)
WHERE m.season = 3
GROUP BY p1.displayname
UNION ALL
SELECT
p2.displayname AS [Player2],
COUNT(p2.displayname) AS [Played],
SUM(IIF(m.player1=m.winner, 1, 0)) AS [Games Won]
FROM ((tblMatch m)
INNER JOIN tblPlayers p2 ON m.player1=p2.id)
WHERE m.season = 3
GROUP BY p2.displayname)  AS [InnerQueryAlias]
GROUP BY [InnerQueryAlias].[Player];


来源:https://stackoverflow.com/questions/18436459/grouping-and-joining-a-unioned-table-having-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!