0
我在我的數據庫中有一張包含足球結果的表格,相關列爲matchNumber(基於日期的數字),Result(「W」,「D」或「L」)goalsFor,goalsAg和manager。如何通過/子查詢創建多個MySQL計數/分組?
我有這個疑問:
SELECT COUNT(*) AS P,
(SELECT COUNT(*) FROM match_results WHERE manager = 13 AND Result = "W") AS W,
(SELECT COUNT(*) FROM match_results WHERE manager = 13 AND Result = "D") AS D,
(SELECT COUNT(*) FROM match_results WHERE manager = 13 AND Result = "L") AS L,
SUM(GoalsFor) AS F,
SUM(GoalsAg) AS A,
ROUND((SELECT SUM((((SELECT COUNT(*) FROM match_results WHERE manager = 13 AND Result = "W") * 2) +(SELECT COUNT(*) FROM match_results WHERE manager = 13 AND Result = "D")))/((SELECT COUNT(*) FROM match_results WHERE manager = 13)*2)*100),2) AS pct
FROM match_results WHERE manager = 13;
返回以下結果:
P W D L F A Pct
213 92 49 72 296 247 54.69
這完美的作品。但是,結果會跨越多個季節,我希望打破查詢的輸出以反映這一點。我曾嘗試以下:
SELECT LEFT(matchNumber,4) AS Season,
COUNT(*) AS P,
(SELECT COUNT(*) FROM match_results WHERE manager = 13 AND Result = "W") AS W,
(SELECT COUNT(*) FROM match_results WHERE manager = 13 AND Result = "D") AS D,
(SELECT COUNT(*) FROM match_results WHERE manager = 13 AND Result = "L") AS L,
SUM(GoalsFor) AS F,
SUM(GoalsAg) AS A,
ROUND((SELECT SUM((((SELECT COUNT(*) FROM match_results WHERE manager = 13 AND Result = "W") * 2) +(SELECT COUNT(*) FROM match_results WHERE manager = 13 AND Result = "D")))/((SELECT COUNT(*) FROM match_results WHERE manager = 13)*2)*100),2) AS pct
FROM match_results WHERE manager = 13
GROUP BY Season;
此查詢的結果可以在此圖像中可以看出:
http://www.kidderminsterharriers.com/images/query2.jpg
正如你所看到的, '季節', 'P',「F '和'A'列給了我想要的結果,但剩下的列正在重複總計。因此,我的問題是,如何調整我的查詢,使'W','D'和'L'列在輸出的每一行中給出逐年總計,而不是總數?
感謝您的建議,但它不工作,它「在‘where子句’未知列‘mr.Season’」 – AndrewDFrazier 2009-12-24 00:04:13
好吧,我已經更新了我的答案返回錯誤。它現在使用變量'@ season',似乎在子查詢中起作用 – cmptrgeekken 2009-12-24 00:17:21
是的,這很有效,這正是我剛剛嘗試過的。謝謝。 – AndrewDFrazier 2009-12-24 00:24:49