2

我有两个表: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、Name、Address

这两个表之间的联系是:CustomerAddress,所以我可以根据Address将两者连接起来:

SELECT * FROM CustomerInformation 
JOIN CustomerMeters 
ON CustomerAddress  = Address 

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

谢谢你。

4

3 回答 3

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)
于 2013-08-08T19:34:25.880 回答
2

以下查询将为您提供表中所有记录的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 
于 2013-08-08T19:42:47.257 回答
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)
于 2013-08-08T19:35:15.887 回答