2017-05-11 59 views
0

我正在使用訪問作爲我的數據庫來嘗試按學科級別爲每個學生測試嘗試次數。一些基本信息:學校有很多學生,學生的測試嘗試是按主題記錄的。我希望更新每個SchoolGrade的科目考試總次數。 下面是我的查詢:訪問更新總和錯誤的SQL

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]); 

我收到以下錯誤:

You tried to execute a query that does not include the specified expression 'Total Reading Test Attempts' as part of an aggregate function.

如何解決這個問題?

回答

1

是完整的,這裏是一個全套的查詢來執行更新和事後清理。所有應得的信貸戈登Linoff的答案和Use SELECT inside an UPDATE query

創建表:

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 

清理:

DROP TABLE TempTable 
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 
+0

我收到以下錯誤: 語法錯誤(缺少操作員)在查詢表達式' s.sum_science FROM [SchoolGrade] AS SG INNER JOIN (SELECT s.schoolgrade_id, SUM([讀取測試嘗試])作爲sum_reading, SUM([數學式測試嘗試])作爲sum_math, SUM([科學測試嘗試])作爲sum_science FROM [學生]爲S GROUP BY s.schoolgrade_id )s ON S.schoolgrade_id = SG.id'。 – user908759

+1

它缺少's'別名。此外,Access不會使用JOINS執行更新以進行查詢。如果您嘗試這樣做,則會返回錯誤「操作必須使用可更新查詢」。參見[在UPDATE查詢中使用SELECT](http://stackoverflow.com/questions/871905/use-select-inside-an-update-query)。 –

+0

C珀金斯創建一個表,從工作更新!謝謝! – user908759