用于计算多列条目的SQL查询

时间:2012-04-05 21:30:19

标签: sql sql-server tsql

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

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

tblMatches包含matchID,scorer1ID,scorer2ID,scorer3ID。

我需要运行一个查询来计算玩家得分的总数,并将其与玩家ID一起返回。

我尝试了以下内容:

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

但是,这不能按要求工作,因为计数功能不允许玩家在游戏中得分超过一个目标(例如,如果玩家得分三个目标,他的ID出现在得分者1ID中field,scorer2ID字段和scorer3ID字段,但当需要为3)时,计数只返回值1。

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

试试这个。它使用嵌入式select语句来计算玩家在每个列中显示的次数

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