2017-07-14 127 views
0

我需要劃分兩列的總和在子查詢,通過第三場分組如下:總和分組的子查詢

Team | Score  | MaxScorePossible 
-------------------------------------------- 
A  |  10  |  15 
A  |  12  |  20 
B  |  5  |  15 
B  |  7  |  20 

我的代碼是這樣的:

SELECT (sumScore/sumMaxScore) as Percentage 
FROM 
(SELECT 
    sum(Score) as sumScore 
    FROM tableScore 
    GROUP BY Team) tbl1, 
(SELECT 
    sum(MaxScorePossible) as sumMaxScore 
    FROM tableScore 
    GROUP BY Team) tbl2, 
GROUP By Team 

的輸出我希望是這樣的: A => 0.62,B => 0.34

問題很明顯,我分組子查詢和父查詢,但我不知道如何組並導致另一個類似的組合。

回答

1

你不需要子查詢。

SELECT Team, SUM(Score)/SUM(MaxScorePossible) AS Percentage 
FROM tableScore 
GROUP BY Team 

如果您確實想要使用子查詢,您必須加入它們。

SELECT tbl1.Team, (sumScore/sumMaxScore) as Percentage 
FROM 
    (SELECT 
     Team, sum(Score) as sumScore 
     FROM tableScore 
     GROUP BY Team) tbl1 
JOIN 
    (SELECT 
     Team, sum(MaxScorePossible) as sumMaxScore 
     FROM tableScore 
     GROUP BY Team) tbl2 
ON tbl1.Team = tbl2.Team 
+0

謝謝!非常感激! – DrBorrow