当2列是唯一的时,SQL合并到

时间:2014-11-27 03:59:00

标签: sql-server

当2列唯一时,我尝试将2个表@UserIds@Results合并到@Results

到目前为止我有什么

MERGE INTO @UserIds t
USING (SELECT
          CustomerIdentifier, SalesChannel_Id
       FROM @Results) AS s ON (s.CustomerIdentifier = t.CustomerIdentifier 
                               AND s.SalesChannel_Id = t.SalesChannel_Id)
WHEN NOT MATCHED THEN
    INSERT (CustomerIdentifier, SalesChannel_Id, Searched) 
    VALUES (s.CustomerIdentifier, s.SalesChannel_Id, 0);

合并会产生重复的CustomerIdentifierSalesChannel_Id

E.g。

234@234.com.au  111 0
234@234.com.au  2   0
234@234.com.au  2   0
234@234.com.au  2   0
243@234.com.au  18  0
234@234.com.au  18  0

什么时候应该只包含

234@234.com.au  111 0
234@234.com.au  2   0
234@234.com.au  18  0

1 个答案:

答案 0 :(得分:2)

MERGE语句将在@Results中插入任何重复键,如果它们在@UserIds中不存在,您可以通过添加DISTINCT运算符来避免这种情况

MERGE INTO @UserIds t
USING (SELECT DISTINCT
    CustomerIdentifier,
    SalesChannel_Id
FROM @Results) as s 
ON (s.CustomerIdentifier = t.CustomerIdentifier and s.SalesChannel_Id = t.SalesChannel_Id )
WHEN NOT MATCHED THEN
    INSERT (CustomerIdentifier, SalesChannel_Id, Searched) 
    VALUES (s.CustomerIdentifier,s.SalesChannel_Id, 0);