我会通过使用分析函数来测试是否存在“A”特征,然后加入另一个表以获取 dt。
正如你的问题所写,我认为这就是你所追求的:
with table_a as (select 1 ord, 'A' feature from dual union all
select 1 ord, 'B' feature from dual union all
select 1 ord, 'C' feature from dual union all
select 2 ord, 'B' feature from dual union all
select 2 ord, 'C' feature from dual union all
select 3 ord, 'A' feature from dual union all
select 3 ord, 'C' feature from dual union all
select 4 ord, 'A' feature from dual union all
select 4 ord, 'B' feature from dual),
table_b as (select 1 ord, to_date('01/08/2015', 'dd/mm/yyyy') dt from dual union all
select 2 ord, to_date('01/08/2015', 'dd/mm/yyyy') dt from dual union all
select 3 ord, to_date('01/08/2015', 'dd/mm/yyyy') dt from dual union all
select 4 ord, to_date('31/07/2015', 'dd/mm/yyyy') dt from dual union all
select 5 ord, to_date('31/07/2015', 'dd/mm/yyyy') dt from dual),
res as (select ta.ord,
ta.feature,
max(case when ta.feature = 'A' then 'A' end) over (partition by ta.ord) a_present,
tb.dt
from table_a ta
inner join table_b tb on (ta.ord = tb.ord))
select ord,
feature
from res
where a_present is not null
and to_char(dt, 'mm') != '08';
ORD FEATURE
---------- -------
4 A
4 B
但是,您指出的结果表明,您实际上想要在每个组中都包含“A”并且确实落在 8 月份的结果
with table_a as (select 1 ord, 'A' feature from dual union all
select 1 ord, 'B' feature from dual union all
select 1 ord, 'C' feature from dual union all
select 2 ord, 'B' feature from dual union all
select 2 ord, 'C' feature from dual union all
select 3 ord, 'A' feature from dual union all
select 3 ord, 'C' feature from dual union all
select 4 ord, 'A' feature from dual union all
select 4 ord, 'B' feature from dual),
table_b as (select 1 ord, to_date('01/08/2015', 'dd/mm/yyyy') dt from dual union all
select 2 ord, to_date('01/08/2015', 'dd/mm/yyyy') dt from dual union all
select 3 ord, to_date('01/08/2015', 'dd/mm/yyyy') dt from dual union all
select 4 ord, to_date('31/07/2015', 'dd/mm/yyyy') dt from dual union all
select 5 ord, to_date('31/07/2015', 'dd/mm/yyyy') dt from dual),
res as (select ta.ord,
ta.feature,
max(case when ta.feature = 'A' then 'A' end) over (partition by ta.ord) a_present,
tb.dt
from table_a ta
inner join table_b tb on (ta.ord = tb.ord))
select ord,
feature
from res
where a_present is not null
and to_char(dt, 'mm') = '08';
ORD FEATURE
---------- -------
1 A
1 B
1 C
3 A
3 C