分组和加入联合表。有问题

时间:2013-08-26 04:08:51

标签: vb.net ms-access group-by union jointable

前几天我问了一个问题并收到了一些非常有用的信息,这些信息帮助我做到了这一点。但是我现在无法使用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列,并计算该玩家所玩游戏的数量以及从这些游戏中计算他们赢得游戏的次数。

由于

1 个答案:

答案 0 :(得分:0)

您是不是只在外部查询中添加了另一个组:

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];