2017-07-14 73 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