T-SQL MERGE:每个GROUP BY表达式必须至少包含一个不是外部引用的列

问题描述 投票:1回答:1

当使用SELECT CONCAT(SOURCE.OrderNo, '_', SOURCE.OrderLine), MAX(SOURCE.LastDate) GROUP BY CONCAT(SOURCE.OrderNo, '_', SOURCE.OrderLine)SELECT CONCAT(TARGET.OrderNo, '_', TARGET.OrderLine), MAX(TARGET.LastDate) GROUP BY CONCAT(TARGET.OrderNo, '_', TARGET.OrderLine)

MERGE dbo.TargetTbl AS TARGET
USING dbo.SourceTbl AS SOURCE 
      ON (TARGET.OrderNo = SOURCE.OrderNo) 
WHEN MATCHED AND EXISTS (SELECT           CONCAT(SOURCE.OrderNo, '_', SOURCE.OrderLine)
                                         ,MAX(SOURCE.LastDate)
                         GROUP BY         CONCAT(SOURCE.OrderNo, '_', SOURCE.OrderLine)
                         INTERSECT SELECT CONCAT(TARGET.OrderNo, '_', TARGET.OrderLine)
                                         ,MAX(TARGET.LastDate)
                         GROUP BY         CONCAT(TARGET.OrderNo, '_', TARGET.OrderLine)
                        )
THEN UPDATE SET TARGET.IsBlocked = 1;

我收到此错误:

每个GROUP BY表达式必须至少包含一个不是外部引用的列。

我搜索并找到了一些解决方案,但它们都不适用于我的查询或至少我不知道如何。任何帮助将不胜感激。

编辑:我肯定可以在SOURCE和TARGET表中有两个相同的行,它会抛出这个错误:

MERGE语句尝试多次更新或删除同一行。当目标行与多个源行匹配时会发生这种情况。 MERGE语句不能多次更新/删除目标表的同一行。优化ON子句以确保目标行最多匹配一个源行,或使用GROUP BY子句对源行进行分组。

通过添加GROUP BY,它给出了上面提到的外部参考错误。

sql-server tsql merge
1个回答
1
投票

您不需要INTERSECT,因为Merge会比较Source和Target表之间的数据。尝试以下内容。

MERGE dbo.TargetTbl AS TARGET
USING 
(
    SELECT  CONCAT(OrderNo, '_', OrderLine) AS OrderLineNo,
            MAX(LastDate) AS LastDate
    FROM dbo.SourceTbl
    GROUP BY CONCAT(SOURCE.OrderNo, '_', SOURCE.OrderLine)
) AS SOURCE 
    ON SOURCE.OrderNo = TARGET.OrderNo 
    AND SOURCE.OrderLineNo = CONCAT(TARGET.OrderNo, '_', TARGET.OrderLine)
    AND SOURCE.LastDate = TARGET.LastDate
WHEN MATCHED THEN UPDATE 
        SET TARGET.IsBlocked = 1;
© www.soinside.com 2019 - 2024. All rights reserved.