我试图在MySQL中使用Joins和sum对多个表进行求和,但没有取得太大的成功。
我的表(删除不必要的列)
学生
idStudent studentname studentyear
1 foobar 11
2 barfoo 11
3 thing 8Athletics_Results
idResult idStudent points
1 1 14
2 1 11
3 3 7
4 2 9Team_Results
idTeamResults year points
1 11 9
2 8 8
3 7 14让我来解释一下这些桌子,因为我承认它们的名字和设计都很差。
学生掌握每个学生的基本信息,包括他们的年和名字。每个学生都有一个唯一的ID。
Athletics_Results存储竞技项目的结果。idStudent列是外键,与学生列中的idStudent相关。因此,学生足球(idStudent 1)在这个例子中得了14分和11分。
Team_Results商店是由不止一个学生参加的事件产生的。它只存储年度组和点数。
目标
我希望每年都能得到一个积分-- athletics_results和team_results的总和。例:
year points
7 14 <-- No results in a_r, just 14 points in t_r
8 15 <-- 7 points in a_r (idResult 4) and 8 in t_r
11 43 <-- 14, 11, 9 points in a_r and 9 in t_r为了测试目的我尝试了什么,我还没有尝试将分数和t_r分数组合在一起,而是将它们作为两列,这样我就可以看到发生了什么。
我尝试的第一个查询是:
SELECT students.studentyear as syear, SUM(athletics_results.points) as score, SUM(team_results.points) as team_score
FROM students
JOIN team_results ON students.studentyear = team_results.year
JOIN athletics_results ON students.idStudent = athletics_results.idStudent
GROUP BY syear;这为每年提供了不同的行(如所需),但有错误的总数。我知道这是因为没有分组连接。
然后我创建了以下代码:
SELECT studentyear as sYear, teamPoints, AthleticsPoints
FROM students st
JOIN (SELECT year, SUM(tm.points) as teamPoints
FROM team_results tm
GROUP BY year) tr ON st.studentyear = tr.year
JOIN (SELECT idStudent, SUM(atr.points) as AthleticsPoints
FROM athletics_results atr
) ar ON st.idStudent = ar.idStudent它给出了正确的总数,但只返回了一年组行(例如11年级的分数)。
编辑- SQLFiddle这里:http://sqlfiddle.com/#!9/dbc16/.这是与我的实际测试数据,这是一个更大的样本比我在这里张贴的数据。
发布于 2015-04-18 20:29:29
可以用多种方式完成。我的第一个想法是:
SELECT idStudent, year, SUM(points) AS totalPoints FROM (
SELECT a.idStudent, c.year, a.points+b.points AS points
FROM students a
INNER JOIN Athletics_Results b ON a.idStudent=b.idStudent
INNER JOIN Team_Results c ON a.studentyear=c.year) d
GROUP BY idStudent,yearhttps://stackoverflow.com/questions/29722132
复制相似问题