SQL Server比较多少数据匹配,并且仅在一个表中

时间:2013-08-08 19:31:23

标签: sql sql-server

我有两张桌子: CustomerInformation

CustomerName CustomerAddress CustomerID LocationID   BillDate
CITY - 1    500 N ST    47672001    29890   2012-07-20 00:00:00.000 0
CITY - 1    500 N ST    47672001    29890   2012-07-20 00:00:00.000 6890
CITY - 1    500 N ST    47672001    29890   2012-08-17 00:00:00.000 0
CITY - 9    510 N ST    47643241    29890   2012-08-17 00:00:00.000 5460
CITY - 4213 500 S ST    43422001    29890   2012-09-17 00:00:00.000 0
CITY - 5    100 N ST    23272001    29890   2012-09-17 00:00:00.000 4940
CITY - 3    010 N ST    43323001    29890   2012-10-19 00:00:00.000 0
CITY - 78   310 N ST    12222001    29890   2012-10-19 00:00:00.000 5370

和CustomerMeters有三列:ID,名称,地址

这两个表之间的连接是:CustomerAddress,所以我可以根据地址加入这两个:

SELECT * FROM CustomerInformation 
JOIN CustomerMeters 
ON CustomerAddress  = Address 

现在,问题是我有如此多的记录(在CustomerInformation中超过20000),我是否列出了两个表中匹配的记录数,以及仅在CustomerInformation表中有多少记录?

谢谢。

3 个答案:

答案 0 :(得分:2)

加入产生的记录数:

SELECT COUNT(*) 
FROM CustomerInformation 
JOIN CustomerMeters 
  ON CustomerAddress = Address

CustomerInformation表格中独占的记录数:

SELECT COUNT(*) 
FROM CustomerInformation AS CI -- Records in CustomerInformation
WHERE NOT EXISTS(SELECT *      -- that are not in CustomerMeters
                 FROM CustomerMeters AS CM
                 WHERE CM.Address = CI.CustomerAddress)

答案 1 :(得分:2)

followng查询将为您提供CustomerInformation表中的所有记录列表以及标记列MATCH,如果CustomerMeters表中存在相应的记录,则该列将包含1,否则为零。

SELECT  CI.ID
        ,Ci.Name
        ,CI.CustomerAddress 
        ,CASE WHEN CM.Address IS NULL THEN 0 ELSE 1 END AS MATCH
FROM    CustomerInformation CI
LEFT OUTER JOIN
        CustomerMeters CM 
ON      CM.Address = CI.CustomerAddress 

答案 2 :(得分:0)

select
    C.grp, count(*)
from CustomerInformation as ci
    left outer join CustomerMeters as cm on cm.CustomerAddress = ci.Address
    outer apply (
        select
            case
                when cm.ID is not null then 'Number of records in both tabless'
                else 'not in CustomerMeters'
            end as grp
    ) as C
group by C.grp

--number of records in both tables
select count(*)
from CustomerInformation as ci
where ci.Address in (select cm.CustomerAddress from CustomerMeters as cm)

--number of records in CustomerInformation which are not in CustomerMeters
select count(*)
from CustomerInformation as ci
where ci.Address not in (select cm.CustomerAddress from CustomerMeters as cm)