2

我有一个包含两个表 tblPlayers 和 tblMatches 的数据库。

tblPlayers 包含以下字段:playerID、playerName。

tblMatches 包含 matchID、scorer1ID、scorer2ID、scorer3ID。

我需要运行一个查询来计算球员的总进球数,并将其与他们的 playerID 一起返回。

我尝试了以下方法:

SELECT
tblPlayers.playerID, tblPlayers.playerName, count(*) AS goals
FROM
tblPlayers, matches
WHERE
(tblPlayers.playerID = tblMatches.scorer1ID
OR
tblPlayers.playerID = tblMatches.scorer2ID
OR
tblPlayers.playerID = tblMatches.goalscorer3ID)
GROUP BY tblPlayers.playerID
ORDER BY goals DESC

但是,这并不能按要求工作,因为 count 函数不允许球员在一场比赛中得分超过一个球(例如,如果球员进了三个球,他的 ID 将出现在 scorer1ID 字段, scorer2ID字段和 scorer3ID 字段,但计数只返回值 1,当它需要为 3 时)。

希望这是有道理的,过去几天我一直在努力解决这个问题!非常感谢任何帮助。

4

3 回答 3

2
SELECT
    playerID,
    playerName,
    SUM(goals) AS goals
FROM 
(
    SELECT p.playerID, p.playerName, COUNT(*) AS goals
    FROM 
        tblPlayers p
        JOIN tblMatches m ON m.scorer1ID = p.playerID
    GROUP BY p.playerID, p.playerName

    UNION ALL

    SELECT p.playerID, p.playerName, COUNT(*) AS goals
    FROM 
        tblPlayers p
        JOIN tblMatches m ON m.scorer2ID = p.playerID
    GROUP BY p.playerID, p.playerName

    UNION ALL

    SELECT p.playerID, p.playerName, COUNT(*) AS goals
    FROM 
        tblPlayers p
        JOIN tblMatches m ON m.scorer3ID = p.playerID
    GROUP BY p.playerID, p.playerName
) sub
GROUP BY playerID, playerName

或者,这是一个一次性完成的查询:

SELECT 
    p.playerID, 
    p.playerName, 
    SUM (
        CASE WHEN p.playerID = m.scorer1ID THEN 1 ELSE 0 END +
        CASE WHEN p.playerID = m.scorer2ID THEN 1 ELSE 0 END +
        CASE WHEN p.playerID = m.scorer3ID THEN 1 ELSE 0 END
    ) AS goals
FROM 
    tblPlayers p
    JOIN tblMatches m ON p.playerID IN (m.scorer1ID, m.scorer2ID, m.scorer3ID)
GROUP BY p.playerID, p.playerName
于 2012-04-05T21:41:07.560 回答
0

这是一个糟糕的表格设计,但如果你坚持使用它,那么应该执行以下操作:

SELECT
tblPlayers.playerID, tblPlayers.playerName,  
(select count(*) from tblMatches m where p.playerId = m.Scoreer1Id)
+
(select count(*) from tblMatches m where p.playerId = m.Scoreer2Id)
+
(select count(*) from tblMatches m where p.playerId = m.Scoreer3Id)
from tblPlayers p
于 2012-04-05T21:42:22.413 回答
0

试试这个。它使用嵌入式选择语句来计算玩家在每列中出现的次数

SELECT tblPlayers.playerID, tblPlayers.playerName, ((SELECT COUNT(*) FROM tblPlayers, matches WHERE tblPlayers.playerID = tblMatches.scorer1ID) + (SELECT COUNT(*) FROM tblPlayers, matches WHERE tblPlayers.playerID = tblMatches.scorer2ID) + (SELECT COUNT(*) FROM tblPlayers, matches WHERE tblPlayers.playerID = tblMatches.scorer2ID)) As [GoalsScored] 
FROM tblPlayers
WHERE
(tblPlayers.playerID = tblMatches.scorer1ID
OR
tblPlayers.playerID = tblMatches.scorer2ID
OR
tblPlayers.playerID = tblMatches.goalscorer3ID)
GROUP BY tblPlayers.playerID
ORDER BY goals DESC
于 2012-04-05T21:44:55.647 回答