簡體   English   中英

SQL Server比較僅在一個表中匹配的數據量

[英]SQL Server Comparing how many data matches, and only in one tables

我有兩個表: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,因此我可以基於Address將兩個表連接起來:

SELECT * FROM CustomerInformation 
JOIN CustomerMeters 
ON CustomerAddress  = Address 

現在,問題是我有這么多記錄(CustomerInformation中的20000以上),難道我沒有列出兩個表中匹配的記錄數,以及CustomerInformation表中只有多少條記錄?

謝謝。

聯接產生的記錄數:

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)

隨后的查詢將為您提供CustomerInformation表中所有記錄的列表和一個標志列MATCH ,如果CustomerMeters表中存在核心響應記錄,則該標志列將包含1,否則為0。

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 
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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM