具有UNION条件的SQL查询比较

时间:2018-12-22 15:55:37

标签: sql sql-server

我们在同事的帮助下,编译了以下sql代码,以比较并去除出现在两个表中的记录。

WITH cmn AS 
(
    SELECT a.CDC_TYPE
    FROM tabled a 
    INNER JOIN tablee b ON a.COUNTRY_ID = b.COUNTRY_ID
                        AND a.PK_LOYALTYACCOUNT = b.PK_LOYALTYACCOUNT 
                        AND a.CDC_TYPE = 'U'
)
SELECT 
    1 AS is_deleted, 
    a.* 
FROM
    tabled a 
INNER JOIN 
    cmn ON a.CDC_TYPE = cmn.CDC_TYPE 

UNION ALL 

SELECT 
    0 AS is_deleted, 
    b.* 
FROM
    tablee b 
INNER JOIN 
    cmn ON b.CDC_TYPE = cmn.CDC_TYPE

示例数据来自下表:

tabled

tablee

查询的预期结果应该看起来像这样:

correctout

但是,输出如下所示:

incorrectoutput

有人可以让我知道我要去哪里了吗

谢谢

1 个答案:

答案 0 :(得分:1)

您应将查询写为:

; with cmn as 
  ( SELECT a.CDC_TYPE,
           a. PK_LOYALTYACCOUNT, --Add these also in CTE result set 
           a.COUNTRY_ID --Add these also in CTE result set 
    FROM    a  
    INNER JOIN  b  
    ON a.COUNTRY_ID = b.COUNTRY_ID 
    AND a.PK_LOYALTYACCOUNT = b.PK_LOYALTYACCOUNT  
    AND a.CDC_TYPE = 'U'
    )
 SELECT 1 AS is_deleted, 
        a.*  
 FROM    a  
 INNER JOIN cmn  
 ON a.CDC_TYPE = cmn.CDC_TYPE 
 and  a.COUNTRY_ID = cmn.COUNTRY_ID  
 AND a.PK_LOYALTYACCOUNT = cmn.PK_LOYALTYACCOUNT

 UNION ALL  
 SELECT 0 AS is_deleted, 
        b.*  
 FROM    b  
 INNER JOIN cmn  
 ON b.CDC_TYPE = cmn.CDC_TYPE 
 and b.COUNTRY_ID = cmn.COUNTRY_ID 
 AND b.PK_LOYALTYACCOUNT = cmn.PK_LOYALTYACCOUNT

当您从CTE仅返回CDC_TYPE'U'并将值再次与表a和b联接时,实际上它们分别与表a和b的所有行相乘,因为它们都符合条件{{ 1}}。为避免获得所有结果,您应该在CTE结果集中包含a.CDC_TYPE = cmn.CDC_TYPEPK_LOYALTYACCOUNT。  Test code here...