如何在SQL查询中找到剩余的行

时间:2017-08-01 00:42:45

标签: sql sql-server inner-join

我使用两个数据源(表)ODS.dbo.Account_Address__cPAF.dbo.Delivery_Addresses来对表ODS.dbo.Account_Address__c中的地址数据进行统计汇总。表PAF.dbo.Delivery_Addresses用于查找和内连接。

感兴趣的所有数据都是自CreatedDate=2016-09-28以来的所有行以及IsCurrent=1之前2016-09-28的所有行。

表1

SELECT DPID__c,CreatedDate
FROM ODS.dbo.Account_Address__c
WHERE CreatedDate>='2016-09-28'

UNION ALL

SELECT DPID__c,CreatedDate
FROM ODS.dbo.Account_Address__c
WHERE CreatedDate<'2016-09-28' AND IsCurrent=1 

完全265773 rows

然后我通过内部联接使用PAF.dbo.Delivery_Addresses对数据进行子集化,返回241565 rows

表2

SELECT 
     aa.DPID__c, aa.CreatedDate     
FROM 
     ODS.dbo.Account_Address__c aa ,PAF.dbo.Delivery_Addresses da
WHERE
     aa.DPID__c = CONVERT(VARCHAR,da.DELIVERY_POINT_ID)
     AND aa.CreatedDate>='2016-09-28'
     AND aa.DPID__c IS NOT NULL

UNION ALL

SELECT
     aa.DPID__c,aa.CreatedDate
FROM    
     ODS.dbo.Account_Address__c aa ,PAF.dbo.Delivery_Addresses da
WHERE
     aa.DPID__c = CONVERT(VARCHAR,da.DELIVERY_POINT_ID)
     AND aa.CreatedDate<'2016-09-28'
     AND aa.DPID__c IS NOT NULL
     AND aa.IsCurrent=1

随后我还检查了另外两个子集。

表3

DPID__c的空11170 rows

SELECT DPID__c,CreatedDate
FROM ODS.dbo.Account_Address__c
WHERE CreatedDate>='2016-09-28' AND DPID__c IS NULL 

UNION ALL

SELECT DPID__c,CreatedDate
FROM ODS.dbo.Account_Address__c
WHERE CreatedDate<'2016-09-28' AND IsCurrent=1 AND DPID__c IS NULL 

拒绝内部联接集,12982 rows返回。

表4

SELECT a.DPID__c,a.CreatedDate
FROM
(
 SELECT DPID__c,CreatedDate
 FROM ODS.dbo.Account_Address__c
 WHERE CreatedDate>='2016-09-28' AND DPID__c IS NOT NULL

 UNION ALL

 SELECT DPID__c,CreatedDate
 FROM ODS.dbo.Account_Address__c
 WHERE CreatedDate<'2016-09-28' AND DPID__c IS NOT NULL AND IsCurrent=1
) a

EXCEPT

SELECT t.DPID__c,t.CreatedDate
FROM
(
 SELECT 
    aa.DPID__c, aa.CreatedDate      
 FROM   
    ODS.dbo.Account_Address__c aa ,PAF.dbo.Delivery_Addresses da
 WHERE
    aa.DPID__c = CONVERT(VARCHAR,da.DELIVERY_POINT_ID)
    AND aa.CreatedDate>='2016-09-28'
    AND aa.DPID__c IS NOT NULL

 UNION ALL

 SELECT
   aa.DPID__c, aa.CreatedDate           
 FROM   
   ODS.dbo.Account_Address__c aa ,PAF.dbo.Delivery_Addresses da
 WHERE
   aa.DPID__c = CONVERT(VARCHAR,da.DELIVERY_POINT_ID)
   AND aa.CreatedDate<'2016-09-28'
   AND aa.DPID__c IS NOT NULL
   AND aa.IsCurrent=1
 ) t

经过验证,Count_Row(Table 1)>Count_Row(Table 2)+Count_Row(Table 3)+Count_Row(Table 4)并且在56中仍有Table 1个额外行,但在其他任何表格中都没有。

任何人都可以帮忙建议如何发生这种差距,如何检测剩余的56 rows

干杯

1 个答案:

答案 0 :(得分:1)

您的except删除了重复项。你应该使用except all。 不幸的是,SQL服务器没有except all,但这可能是您的线路被丢弃的地方。

检查每个查询中的唯一行,您应该具有相同的数字。