![](/img/trans.png)
[英]How to display data in SQL from multiple tables, but only if one column data matches another column?
[英]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.