SQL - 聚合可能不会出现在 UPDATE 语句的集合列表中

SQL - An aggregate may not appear in the set list of an UPDATE statement

大家好,美好的一天。你能帮我更正这个 SQL 序列吗?

MERGE INTO table2 WITH (HOLDLOCK) AS target
USING
(
  SELECT column1,
         AccessDate,
         AccessCount,
         column4,
         column5, 
         column6, 
         column7, 
         column8
  FROM  table1
  GROUP BY column1, column4, column5, column6, column7, column8
) AS source
ON target.column1 = source.column1 AND
   target.column5 = source.column5 AND
   target.column6 = source.column6 AND
   target.column7 = source.column7 AND
   target.column8 = source.column8
WHEN MATCHED THEN 
UPDATE SET target.LastAccessDate = MAX(source.AccessDate),
   target.LastWeeklyAccessCount = (SELECT SUM(source.AccessCount))
WHEN NOT MATCHED BY TARGET THEN
   INSERT (column1, LastAccessDate, LastWeeklyAccessCount, column4, column5, column6, column7, column8)
    VALUES (source.column1, source.AccessDate, source.AccessCount, source.column4, source.column5, source.column6, source.column7, source.column8);

当我尝试 运行 时遇到 "aggregate may not appear in the set list of an UPDATE statement" 错误,因为以下两行:

target.LastAccessDate = MAX(source.AccessDate),
target.LastWeeklyAccessCount = (SELECT SUM(source.AccessCount))

我的代码应该更新目标 AccessDate 为组中 AccessDates 的最大值,LastWeeklyAccessCount 为组中计数的总和。

如果找不到匹配的记录,则插入。大约 2 年前,我曾与 SQL 一起工作过,但记不太清了,所以希望得到任何帮助。

错误是因为源语句的select列列表中的AccessDate,AccessCount没有出现在group by列表中:

    MERGE INTO table2 WITH (HOLDLOCK) AS target
    USING
    (
      SELECT column1,
             MAX(AccessDate) AS AccessDate,
             SUM(AccessCount) AS AccessCount,
             column4,
             column5, 
             column6, 
             column7, 
             column8
      FROM  table1
      GROUP BY column1, column4, column5, column6, column7, column8
    ) AS source
    ON target.column1 = source.column1 AND
       target.column5 = source.column5 AND
       target.column6 = source.column6 AND
       target.column7 = source.column7 AND
       target.column8 = source.column8
    WHEN MATCHED THEN 
    UPDATE SET target.LastAccessDate = source.AccessDate,
       target.LastWeeklyAccessCount = source.AccessCount
    WHEN NOT MATCHED BY TARGET THEN
       INSERT (column1, LastAccessDate, LastWeeklyAccessCount, column4, column5, column6, column7, column8)
        VALUES (source.column1, source.AccessDate, source.AccessCount, source.column4, source.column5, source.column6, source.column7, source.column8);