0

我有 2 个结构相同的表。

字段 1 INT
字段 2 VARCHAR(32)

查询必须为表 2 中的所有记录获取不同的字段 1,其中匹配相同的计数和字段 2 的值,而不考虑字段 1 的值 - 只有按字段 1 的计数分组的必须匹配。

示例数据:

表 1

1个
1乙
2℃
2 天
2 E
3G
3小时

表 2

8个
8乙
9 E
9天
9℃
10楼
11克
11小时

查询的结果应该是

8
9
11

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

4

2 回答 2

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在这里

于 2013-06-08T16:25:32.437 回答
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 在这里

于 2013-06-08T16:24:31.977 回答