SQL intersect获取所有匹配行

SQL intersect获取所有匹配行,sql,sql-server,Sql,Sql Server,我有两张结构相同的桌子 FIELD 1 INT FIELD 2 VARCHAR(32) 字段1整型 字段2 VARCHAR(32) 查询必须为表2中的所有记录获取不同的字段1,其中字段1与字段2的相同计数和值相匹配,而不考虑字段1的值-只有字段1的分组计数必须匹配 示例数据: 表1 1 A 1 B 2 C 2 D 2 E 3 G 3 H 1A 1b 2 C 二维 2e 3g 3小时 表2 8 A 8 B

我有两张结构相同的桌子

FIELD 1 INT FIELD 2 VARCHAR(32) 字段1整型 字段2 VARCHAR(32) 查询必须为表2中的所有记录获取不同的字段1,其中字段1与字段2的相同计数和值相匹配,而不考虑字段1的值-只有字段1的分组计数必须匹配

示例数据:

表1

1 A 1 B 2 C 2 D 2 E 3 G 3 H 1A 1b 2 C 二维 2e 3g 3小时 表2

8 A 8 B 9 E 9 D 9 C 10 F 11 G 11 H 8 A 8 B 9 E 9天 9 C 10楼 11克 11小时 查询结果应为

8 9 11 8. 9 11
我已经尝试了多种Intersect和Group By的组合,但我无法做到这一点。谢谢

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是。

请尝试:

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。

这非常有效,感谢SQLFiddle启动。分享这种解决问题的方式真是太酷了。你是个学者,我的朋友。一个比我更简洁的答案——我必须记住它。(我想我从窗口函数发明之前就开始做这些查询了。)谢谢,这与我失败的尝试类似,但你的尝试确实有效,你只用一句话就完成了。是的,我的错误,我纠正了这一点。