2012-04-05 57 views
2

我有一個包含兩個表tblPlayers和tblMatches的數據庫。SQL查詢來計算多列中的條目

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 

然而,這是不工作的要求,作爲計數功能不允許的事實,一個球員可以在一場比賽中得分超過一個目標(例如,如果玩家獲得三個目標,他的ID出現在scorer1ID字段,scorer2ID字段和scorer3ID字段中,但是當它需要爲3時,count只返回值1。

希望有道理,過去幾天我一直在撕掉我的頭髮,試圖解決這個問題!任何幫助不勝感激。

+1

如果比賽中超過3個目標會發生什麼? – barsju 2012-04-05 21:39:21

+0

你是這樣設置表格嗎?我認爲有更有效的方法來做到這一點。 – zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 2012-04-05 21:41:49

回答

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 
+0

+1,並感謝我對我現在刪除的答案upvote。我相信你看到我之前就已經開始了。在JOIN btw上很好地使用'IN'。 – 2012-04-05 21:58:59

+0

太棒了,非常感謝您的幫助。真的很感激它。 – 2012-04-06 07:27:39

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