2014-09-23 33 views
0

感谢您的回复,但如果方案扩展到仅添加第三个Group_ID且只有2个GroupNames,它也会提取。 请帮我写一个匹配2个表的查询,找到第二个表中所有条目匹配的组ID。匹配SQL表并查找每个组中是否存在条目

表1

Group_Id GroupNames  GroupValues  
111   G1    A  
111   G1    B  
111   G1    C  
111   G2    D  
111   G2    E  
111   G2    F  
111   G3    G  
222   G1    A  
222   G1    B  
222   G1    C  
222   G2    E  
222   G2    F  
222   G3    G 
333   G3    G 
333   G1    B 
333   G1    C 

表2:

GroupValues  
B  
D  
G 
H 

OUTPUT

111 

查询建议立即进行删除的输出d为“111”,因为它对所有三个组名称“G1,G2,G3”至少有一个条目。 “222”缺少组名称G2的条目,因此不会返回。 请协助。

回答

1

您可以聚集和having条款做到这一点:

select t1.Group_Id 
from table1 t1 inner join 
    table2 
    on t2.GroupValues = t1.GroupValues 
group by t1.Group_id 
having count(distinct t1.GroupValues) = (select count(distinct GroupValues) from table2); 

注意,distinct是没有必要的,如果你知道有没有重复的值。

+0

这也工作**从表1选择T1 t1.Group_Id 通过t1.Group_id 具有计数(不同t1.GroupValues)=(内部连接 table2的T2 上t2.GroupValues = t1.GroupValues 组从table2中选择count(distinct GroupValues)); – Piyush 2014-09-23 18:41:28

+0

@Piyush。 。 。我不清楚你的评论中的查询与我的回答中的查询不同,只不过你已经在count(distinct)(这是一件好事)中限定了'GroupValues'。 – 2014-09-23 19:01:23

+0

@戈登......我的意思是你的查询工作得很好......但是GroupNames并没有被考虑在内。 – Piyush 2014-09-30 18:07:37

0

发布了两个解决方案,一个是对Gordon Linoff提出的建议的一点修改,另一个是新的解决方案。

1)联视图T1添加,柜面如果一个特定GROUP_ID

select t1.Group_Id 
from (select distinct Group_Id,GroupValues from table1)t1 inner join 
    table2 
    on t2.GroupValues = t1.GroupValues 
group by t1.Group_id 
having count(distinct GroupValues) = (select count(distinct GroupValues) from table2) 

2)在SELECT波纹管减去内具有重复GroupValues,用于识别所述GROUP_ID的其是未完成(或具有group_id和GroupValues的所有组合)。这些id将从table1中存在的所有group_id中移除,因此是结果。

select distinct group_id 
from table1 
minus 
select distinct Group_Id 
from Table2 t2,(select distinct Group_Id from Table1) t1 
where not exists (select 1 
        from Table1 t11 
        where t1.Group_Id = t11.Group_Id 
        and t11.GroupValues = t2.GroupValues) 
相关问题