使用Sum错误访问更新SQL

时间:2017-05-11 22:05:32

标签: sql ms-access inner-join

我正在使用access作为我的数据库来尝试按学科为每个学生的主题测试尝试次数。一些基本信息:学校的学生有很多学生,学生的考试成绩是按科目记录的。我想更新每个SchoolGrade的主题测试总数。 以下是我的询问:

UPDATE [SchoolGrade] AS SG
INNER JOIN [Student] AS S ON S.schoolgrade_id = SG.id
SET SG.[Total Reading Test Attempts] = SUM(S.[Reading Test Attempts] ), 
SG.[Total Math Test Attempts] = SUM(S.[Math Test Attempts] ), 
SG.[Total Science Test Attempts] = SUM(S.[ScienceTest Attempts] );

我收到以下错误:

  

您尝试执行不包含指定的查询   表达式“总读数测试尝试”作为聚合的一部分   功能

如何解决此错误?

2 个答案:

答案 0 :(得分:1)

您需要在执行JOIN之前进行汇总。我认为这将在MS Access中起作用:

UPDATE SG
    SET [Total Reading Test Attempts] = s.sum_reading, 
        [Total Math Test Attempts] = s.sum_math, 
        [Total Science Test Attempts] = s.sum_science
    FROM [SchoolGrade] AS SG INNER JOIN
         (SELECT s.schoolgrade_id,
                 SUM([Reading Test Attempts]) as sum_reading,
                 SUM([Math Test Attempts]) as sum_math,
                 SUM([Science Test Attempts]) as sum_science
          FROM [Student] AS s
          GROUP BY s.schoolgrade_id
         ) s
         ON S.schoolgrade_id = SG.id

答案 1 :(得分:1)

要完成,这里有一整套查询来执行更新并在之后进行清理。所有应归功于Gordon Linoff的回答和Use SELECT inside an UPDATE query

创建表格:

<div id="parent" style="background-color: pink;">
    <div id="child1" style="background-color: gray; display: inline-block; width: 20%;">
        div1
    </div>

    <div id="child2" style="background-color: blue; display: inline-block">
        div2
    </div>

    <div id="child2" style="background-color: violet; display: hidden; width: 20%;">
        div3
    </div>
</div>

执行更新:

SELECT s.schoolgrade_id,
             SUM([Reading Test Attempts]) as sum_reading,
             SUM([Math Test Attempts]) as sum_math,
             SUM([Science Test Attempts]) as sum_science
INTO TempTable
FROM [Student] AS s
GROUP BY s.schoolgrade_id

清理:

UPDATE SG
SET [Total Reading Test Attempts] = s.sum_reading, 
    [Total Math Test Attempts] = s.sum_math, 
    [Total Science Test Attempts] = s.sum_science
FROM [SchoolGrade] AS SG INNER JOIN
     TempTable AS s
     ON S.schoolgrade_id = SG.id