【问题标题】:Wrong calculation in Sum()Sum() 中的错误计算
【发布时间】:2017-10-31 11:07:48
【问题描述】:

你好,我有 2 张桌子,我想加上它。

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 或其他。

【问题讨论】:

  • 能不能用表格的形式来展示数据。像THIS 或向我们展示什么是 db 架构,不确定那个结构是什么。但猜测是你需要UNION 而不是JOIN
  • 能否提供输入表结构和预期输出?
  • 不要在问题标题中加上“已解决”。 接受解决您问题的答案。

标签: sql sql-server select sum sql-query-store


【解决方案1】:

使用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

【讨论】:

    【解决方案2】:

    我认为 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2022-11-11
      相关资源
      最近更新 更多