查找和计数具有差异列更改顺序的两个表

时间:2019-05-19 12:59:11

标签: sql-server

我有两个下表:

表A:

N1 N2 N3
6  11 20

表B:

N1 N2 N3 N4 N5 N6 N7 N8
1  2  5  6  10 12 14 15
1  9  10 15 16 18 19 20
4  5  8  9  10 14 15 16

我想对表B中与表A和结果重复的数据进行计数:

1

1

0

my code (only working for tableb have 1 row):
declare @dem tinyint,
        @t1 tinyint,
        @t2 tinyint,
        @t3 tinyint,
set @dem = 0    
select @t1 = (select [n1] from [tablea])
select @t2 = (select [n2] from [tablea])
select @t3 = (select [n3] from [tablea])
if exists(select 1 from [tableb] where [n1] = @t1 or [n2] = @t1 or [n3] = @t1 or [n4] = @t1 or [n5] = @t1 or [n6] = @t1 or [n7] = @t1 or [n8] = @t1)
begin
    set @dem = @dem + 1
end
if exists(select 1 from [tableb] where [n1] = @t2 or [n2] = @t2 or [n3] = @t2 or [n4] = @t2 or [n5] = @t2 or [n6] = @t2 or [n7] = @t2 or [n8] = @t2)
begin
    set @dem = @dem + 1
end
if exists(select 1 from [tableb] where [n1] = @t3 or [n2] = @t3 or [n3] = @t3 or [n4] = @t3 or [n5] = @t3 or [n6] = @t3 or [n7] = @t3 or [n8] = @t3)
begin
    set @dem = @dem + 1
end
---
select @dem

请支持我的SQL代码。 谢谢。

1 个答案:

答案 0 :(得分:0)

交叉连接表并使用IN运算符。

select
  case when a.n1 in (
    b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8
  ) then 1 else 0 end +
  case when a.n2 in (
    b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8
  ) then 1 else 0 end +
  case when a.n3 in (
    b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8
  ) then 1 else 0 end counter
from tablea a cross join tableb b

请参见demo
结果:

> | counter |
> | ------: |
> |       1 |
> |       1 |
> |       0 |