2

私は2つのテーブルを持っており、両方とも10列と言っていTable1ますTable2

これらの 2 つのテーブルをそれぞれの列の値と比較し、一致する列が 3 つ以上あるレコードのみを選択したいと考えています。

すなわち、

Table1.Col1値が値と一致する AND値が値と一致Table2.Col1する AND値が値と一致する
Table1.Col2Table2.Col2
Table1.Col3Table2.Col3

また

Table1.Col2値が値と一致する AND値が値と一致Table2.Col2するAND 値が値と一致する など...
Table1.Col4Table2.Col4
Table1.Col6Table2.Col6

このためのシンプルでスマートなクエリを作成する方法は?

4

1 に答える 1

2

or 条件で結合し、一致するフィールドの数に基づいてフィルター処理します (最大 4 つのフィールドのみを処理し、必要な数だけ追加します)。

select *
from table1 t1
join table2 t2
  on t1.field1 = t2.field1 
  or t1.field2 = t2.field2
  or t1.field3 = t2.field3
  or t1.field4 = t2.field4
where 
   ( case when t1.field1 = t2.field1 then 1 else 0 end 
   + case when t1.field2 = t2.field2 then 1 else 0 end 
   + case when t1.field3 = t2.field3 then 1 else 0 end 
   + case when t1.field4 = t2.field4 then 1 else 0 end
   ) >= 3

あなたが私のように怠け者なら、このようにすべてのフィールドのステートメントを生成できます。

select 'select * ' union all
select '  from table1 t1' union all
select '  join table2 t2' union all
select '    on 1 = 1 ' union all
select '   and t1.' + t1.name + ' = t2.' + t2.name  from sys.columns t1 join sys.columns t2 on t1.name = t2.name where t1.object_id = object_id('table1') and t2.object_id = object_id('table2')
union all
select 'where ( 0' union all
select '   + case when t1.' + t1.name + ' = t2.' + t2.name + ' then 1 else 0 end ' from sys.columns t1 join sys.columns t2 on t1.name = t2.name where t1.object_id = object_id('table1') and t2.object_id = object_id('table2')
union all 
select '      ) >= 3'

(クエリを実行し、結果をコピーして貼り付けます。)

于 2012-05-30T10:21:28.417 に答える