SQL中的组合

时间:2018-07-15 17:59:07

标签: sql oracle

A

ID      ID_DESC1
1    123              
1    124
1    126
2    127
2    124
2    126
3    130
3    124
3    126
4    131 
4    124
4    126

B

ID_DESC1    DESC
123       ACTIVE
124       SAR
126       SAR1
127       REAL
130       TRI
131       ACC

查询应使用以下组合获取表A联接B的唯一ID 预期结果

Combination1: - ACTIVE,SAR,SAR1
Combination2: - REAL,SAR,SAR1
Combination3: - ACC,SAR,SAR1

结果只能获取ID 1,2,4,而不是3

2 个答案:

答案 0 :(得分:2)

这是一个带有g的组的示例

select a.id
from a join
     b
     on a.id_desc1 = b.id_desc1
group by a.id
having sum(case when b.desc = 'SAR' then 1 else 0 end) > 0 and
       sum(case when b.desc = 'SAR1' then 1 else 0 end) > 0 and
       sum(case when b.desc in ('ACTIVE', 'REAL', 'ACC') then 1 else 0 end) > 0;       

答案 1 :(得分:0)

LISTAGG可以在oracle中回答以上查询