SQL intersect获取所有匹配的行

时间:2013-06-08 16:12:18

标签: sql sql-server

我有2张具有相同结构的表。

FIELD 1      INT
FIELD 2      VARCHAR(32)

查询必须为表2中的所有记录获取Distinct FIELD 1,其中匹配FIELD 2的相同计数和值而不考虑FIELD 1的值 - 仅按FIELD 1的计数分组必须匹配。 / p>

示例数据:

表1

1     A
1     B
2     C
2     D
2     E
3     G
3     H

表2

8     A
8     B
9     E
9     D
9     C
10    F
11    G
11    H

查询结果应为

8
9
11

我已尝试过Intersect和Group By的各种组合,但我无法做到这一点。谢谢!

2 个答案:

答案 0 :(得分:2)

尝试:

with cte as
(select t2.*,
        count(t1.field1) over (partition by t1.field2) t1c,
        count(t2.field1) over (partition by t2.field2) t2c
 from table1 t1
 full join table2 t2 on t1.field2 = t2.field2)
select distinct field1 from cte where t1c=t2c

SQLFiddle here

答案 1 :(得分:0)

SQL中的逻辑有点复杂。这是一个想法(比SQL更简单)。首先计算每个表中每个f1的元素数。你只需要在两者相等的地方保持对。

然后计算每对f1的共同数字。当此计数与列的总计数匹配时,对匹配。

这是执行此操作的SQL:

with t1 as (
       select 1 as f1, 'A' as f2 union all
       select 1, 'B' union all
       select 2, 'C' union all
       select 2, 'D' union all
       select 2, 'E' union all
       select 3, 'G' union all
       select 3, 'H'
     ),
     t2 as (
       select 8 as f1, 'A' as f2 union all
       select 8, 'B' union all
       select 9, 'E' union all
       select 9, 'D' union all
       select 9, 'C' union all
       select 10, 'F' union all
       select 11, 'G' union all
       select 11, 'H'
    )
select driver.f11, driver.f12
from ((select t1.f1 as f11, f2cnt1, t2.f1 as f12, f2cnt2
       from (select t1.f1, count(*) as f2cnt1
             from t1
             group by t1.f1
            ) t1 join
            (select t2.f1, count(*) as f2cnt2
             from t2
             group by t2.f1
            ) t2
            on t1.f2cnt1 = t2.f2cnt2
      )
     ) driver join
     (select t1.f1 as f11, t2.f1 as f12, count(*) as InCommon
      from t1 join
           t2
           on t1.f2 = t2.f2
      group by t1.f1, t2.f1
     ) common
     on driver.f11 = common.f11 and
        driver.f12 = common.f12
where driver.f2cnt1 = common.InCommon;

SQLFiddle是here