比较两个表是否缺少记录

时间:2014-10-13 14:28:05

标签: sql sql-server-2008

如果表-B 的所有记录都存在于 TABLE-A 是当缺少任何一条记录时,> ?比如说,

表A

8000010001

8000011001

8000025001

8000025002


表B

8000010

8000010001

8000010002

8000011

8000011001

8000012

8000012001

8000023

8000023001

8000025

8000025001

8000025002

8000026

8000026001

8000026002


输出

8000010否

8000011是

8000012否

8000023否

8000025是

8000026否


注意 - 请检查表B ,您可以在记录中找到父子关系。例如8000010,8000010 001,8000010 002.父记录(8000010,8000011,8000012 ...)未出现在表A 中。

2 个答案:

答案 0 :(得分:0)

试试这个。

declare @tableA table(id varchar(10))
insert into @tableA values('800010001')
insert into @tableA values('8000011001')
insert into @tableA values('8000025001')
insert into @tableA values('8000025002')

declare @tableB table (id varchar(10))
insert into @tableB values('8000010')
insert into @tableB values('8000010001')
insert into @tableB values('8000010002')
insert into @tableB values('8000011')
insert into @tableB values('8000011001')
insert into @tableB values('8000012')
insert into @tableB values('8000012001')
insert into @tableB values('8000023')
insert into @tableB values('8000023001')
insert into @tableB values('8000025')
insert into @tableB values('8000025001')
insert into @tableB values('000025002')
insert into @tableB values('8000026')
insert into @tableB values('8000026001')
insert into @tableB values('8000026002')

使用左连接可以解决此问题。但最好的方法是用唯一的id映射两个表。

//将tableA与tableB进行比较

select a.id, case when b.id IS null then 'No' else 'Yes' end as Status from @tableA a left join @tableB b on a.id = b.id

//将tableB与tableA进行比较

select b.id, case when a.id IS null then 'No' else 'Yes' end as Status from @tableB b left join @tableA a on a.id = b.id

答案 1 :(得分:0)

我们需要首先拆分记录以建立父子关系

第一个CTE分开了,最好将您的表格更改为此格式,而不是像现在一样将单个ID更改。

ID          parent
8000010     NULL
8000010001  8000010
8000010002  8000010

第二个CTE使用TableA执行JOIN以查找匹配的记录 最后,实际的子计数与第二个CTE的结果相匹配,以将其标记为“否”或“是”

; WITH cte
as
(
SELECT ID, 
       case when Id/10000000 >0 
             then ID/1000
             else NULL
             end as parent
FROM TableB
)
, cte1
as
(
SELECT cte.parent, count(cte.id) as matchedChildrenCount
FROM cte
JOIN tableA A
ON cte.id = A.id

WHERE cte.parent is not null
GROUP BY parent 
)

SELECT T.parent, CASE WHEN cte1.parent is null or T.childrenCount <> cte1.matchedChildrenCount
                      THEN 'No' else 'Yes' 
                      END as value from 
(select parent, 
        COUNT(cte.id) as childrenCount   
 FROM cte 
 where cte.parent is not null
 group by parent 
 ) T
 left join cte1
 on cte1.parent = T.parent