0

前几天我问了一个问题,并收到了一些非常有用的信息,这些信息帮助我走到了这一步。但是,我现在无法使用 UNION/GROUP BY 从表中获取数据。

以下代码是我尝试过的。但我似乎无法找到一种方法将其按 Player 分组。

它是这样显示的。

Jono - 3 - 1
Jono - 1 - 1

当我需要这样展示时

Jono - 4 - 1 

我才刚刚开始,所以如果有更好的方法来执行此代码,请告诉我:)

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)

我的数据库布局是:

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

我真正想做的是显示一个列表,其中玩家姓名可以来自 Player1 或 Player2 列,并计算该玩家玩的游戏数量,并从这些游戏中计算他们赢得比赛的次数。

谢谢

4

1 回答 1

0

你不会在你的外部查询中放另一个 group by:

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];
于 2013-08-26T19:19:19.417 回答