Sum() 计算错误

Wrong calculation in Sum()

嗨,我有 2 个 table,我想加上它。

Table 1 --> StudentId = 1 ,Score = 10 , 20 ,30  , StudentId = 2 ,Score = 5, 5
Table 2 --> StudentId = 1 ,Score = 5, 10 ,15    , StudentId = 2 ,Score = 15, 25
Total = StudentId = 1 ---> 90  , StudentId = 2 ---> 45

我使用这个查询:

Select Sum(tbl_EvaPoint.Score + tbl_ActPoint.Score ), 
       tbl_ActPoint.StudentId 
From tbl_EvaPoint 
JOIN tbl_ActPoint 
  ON tbl_EvaPoint.StudentId = tbl_ActPoint.StudentId 
GROUP BY tbl_ActPoint.StudentId`

一切正常,但我得到了错误的总和,而不是 90 和 45 我得到了 180 和 90 或其他东西。

使用UNION代替JOIN

SELECT student_id, SUM(score)
FROM (SELECT student_id, score FROM Table1
      UNION ALL
      SELECT student_id, score FROM Table2
     ) as T
GROUP BY  student_id

我认为 CTE 更具可读性,但这是个人喜好。

CREATE TABLE #S1 (
     StudentID smallint
    ,Score smallint )

INSERT INTO #S1
SELECT 1, 10;
INSERT INTO #S1
SELECT 1, 20;
INSERT INTO #S1
SELECT 1, 30;
INSERT INTO #S1
SELECT 2, 5
INSERT INTO #S1
SELECT 2, 5;

CREATE TABLE #S2 (
     StudentID smallint
    ,Score smallint )

INSERT INTO #S2
SELECT 1, 5;
INSERT INTO #S2
SELECT 1, 10;
INSERT INTO #S2
SELECT 1, 15;
INSERT INTO #S2
SELECT 2, 15;
INSERT INTO #S2
SELECT 2, 25;

WITH CTE AS (
SELECT 
    StudentID, Score
FROM #S1 
UNION ALL 
SELECT 
    StudentID, Score
FROM #S2 )

SELECT 
     StudentID
    ,SUM(Score) AS TotalScore
FROM CTE
GROUP BY StudentID