首页 > 解决方案 > 在另一个表中查找具有匹配记录的记录

问题描述

我有 2 张桌子

表格1

A | B  | C | D | E | F
a   Mi   2   1  4   001
b   Ma   3   1  4   001
c   NA   1   1  4   001
b   Na   3   1  4   001
d   Na   2   1  4   001
a   Mi   2    1  4   002
b   Na   3    1  4   002
c   Ma   1    1  4   002
d   Na   2   1  4   001

表 2

A | B | C | D | E
a   Mi   2   1  4
b   Ma   3   1  4
c   NA   1   1  4
d   Na   2   1  4

输出 :

F    |  D  
001    1

因此,A、B、C、D、E 和 F 列都是其中特定条件的列。表 1 是需要与表 2 中的数据进行比较的数据表。如果除 Table1 与 Table2 中的记录匹配之外,不同列中的所有F记录都应在输出中选择这些记录。

仅显示 F 列中的 001,因为它在表 2 中给出的相同列中具有相同值的所有 4 行。未选择 F 列中值为 002 的记录,因为它们没有表 2 中的所有行。它们确实有所有 4 行,但带有 b 的记录没有所有相同的匹配值。

最终结果不必是我提到的输出。它可能只是与表 2 中给出的行匹配的所有行。输出就是最后一步的内容。如果我得到与表 2 中所有记录匹配的所有行,我可以实现这一点。

我试过的东西-

select count(A) over(Partition by A,B,C,D,E,F) as rw,* 
into #temp1 
from Table1

select sum(rw) as sm, F 
from #temp1 group by F

select F 
from #temp
where sm = (select count(A) from Table2)

此逻辑的问题之一是 002 可以有 2-3 个重复的行,这可能导致计数等于 table2 中的行数。

标签: sql-servertsql

解决方案


加入表格,然后group by F

select t1.f, max(t1.d) d
from table2 t2 inner join (select distinct * from table1) t1
on t1.A = t2.A and t1.B = t2.B and t1.C = t2.C and t1.D = t2.D and t1.E = t2.E
group by t1.f
having count(*) = (select count(*) from table2)

我使用max(t1.d)它是因为不清楚每个 F 的 D 值是否相同。
请参阅演示
结果:

> f   |  d
> :-- | -:
> 001 |  1

如果您希望 table1 中的行与 table2 中的行匹配,请使用 CTE:

with cte as (
  select t1.f
  from table2 t2 inner join (select distinct * from table1) t1
  on t1.A = t2.A and t1.B = t2.B and t1.C = t2.C and t1.D = t2.D and t1.E = t2.E
  group by t1.f
  having count(*) = (select count(*) from table2)
)
select t1.* from table1 t1
where 
  t1.f in (select f from cte)
  and exists (
    select 1 from table2 t2
    where t1.A = t2.A and t1.B = t2.B and t1.C = t2.C and t1.D = t2.D and t1.E = t2.E
  )

请参阅演示
结果:

> A  | B  |  C |  D |  E | F  
> :- | :- | -: | -: | -: | :--
> a  | Mi |  2 |  1 |  4 | 001
> b  | Ma |  3 |  1 |  4 | 001
> c  | NA |  1 |  1 |  4 | 001
> d  | Na |  2 |  1 |  4 | 001
> d  | Na |  2 |  1 |  4 | 001

如果您想要不同的行,请使用:

select distinct t1.* from table1 t1

反而。
结果:

> A  | B  |  C |  D |  E | F  
> :- | :- | -: | -: | -: | :--
> a  | Mi |  2 |  1 |  4 | 001
> b  | Ma |  3 |  1 |  4 | 001
> c  | NA |  1 |  1 |  4 | 001
> d  | Na |  2 |  1 |  4 | 001

推荐阅读