使用SUM计算SQL中的大量数据组

时间:2014-09-29 10:50:25

标签: sql sql-server count group-by sum

现在,这是一个棘手的问题,因为我正在尝试将每个学生聚集在一起,并且仅在DIST上找到每个学生单元学分的总和。有超过5000名学生,所以以前的例子难以奏效!

以下是原始数据的示例。

表1(tblawardedlearners)

 Student No      Unit      Unit Credit     Grade
  1432          English         1          DIST
  1432          French          2          DIST
  1432          Maths           2          DIST
  1432          History         3          MERIT
  1432          Geography       1          DIST
  1432          Spanish         2          DIST
  1432          Science1        2          MERIT
  1432          Science2        2          PASS
  1431          English         1          DIST
  1431          Maths           3          MERIT
  1431          Science1        1          DIST
  1431          Biology         3          DIST
  1431          Sport           1          MERIT
  1431          French          2          PASS
  1436          Cooking         2          DIST
  1436          Woodwork        1          DIST
  1436          SQL             2          PASS
  1436          CompSci         1          DIST
  1436          Psych           1          MERIT
  1436          Maths           3          PASS

表2(viewunitsonrun)

 Unit Level
ONE THREE TWO TWO THREE THREE ONE ONE THREE TWO TWO THREE THREE ONE ONE THREE TWO TWO THREE THREE ONE

理想情况下,我只需要三列

 Student No      Level      TOTAL Unit Credit   Grade 
  1432           THREE            2               DIST
  1436           THREE            2               DIST

到目前为止,这是我的代码

SELECT SUM (intunitcredit) as TOTALunitcredit, intlearnerID
FROM tblawardedlearners
LEFT JOIN viewunitsonrun
ON tblawardedlearners.strunitcode = viewunitsonrun.strUnitCode
FROM strUnitLevelName = 'THREE'
AND strUnitGrade = 'DIST'
GROUP BY intLearnerID

NB - strunitlevelname是viewunitsonrun(table)所需的唯一列,其他所有列都在tblawardedlearners中。

我得到的结果(每个学生5000个?)。我也尝试添加这些额外的列,但始终标记错误。

提前致谢。

0 个答案:

没有答案