SQL过滤器基于多行数据

时间:2015-05-26 10:44:37

标签: oracle

我发现这有点难以描述,但是这里......我有一张表格如下:

TITLE_CODE    PRODUCT_NUMBER    FORMAT_CODE
1234          A1                OC
1234          A2                HB
1234          A3                PB
2345          B1                OC
2345          B2                HB
3456          C1                OC

我要做的是生成一个查询,我只会提取只有“OC”格式代码并且没有“HB”或“PB”格式代码的记录。

使用Oracle - 非常感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

SELECT TITLE_CODE, PRODUCT_NUMBER FROM {table} WHERE FORMAT_CODE = 'OC';

这样的东西?

答案 1 :(得分:0)

SELECT title_code, product_number, format_code
FROM {table} 
WHERE format_code = 'OC'
AND   title_code NOT IN ( SELECT title_code 
                          FROM  {table}
                          WHERE format_code = 'HB' 
                          OR    format_code = 'PB'
                        );

答案 2 :(得分:0)

这是一种替代方案,对于您的数据而言可能比@ avk的答案更快或更快(您必须测试):

with sample_data (title_code, product_number, format_code) as (select 1234, 'A1', 'OC' from dual union all
                                                               select 1234, 'A2', 'HB' from dual union all
                                                               select 1234, 'A3', 'PB' from dual union all
                                                               select 2345, 'B1', 'OC' from dual union all
                                                               select 2345, 'B2', 'HB' from dual union all
                                                               select 3456, 'C1', 'OC' from dual union all
                                                               select 7890, 'D1', 'OC' from dual union all
                                                               select 7890, 'D2', 'TD' from dual)
select title_code,
       product_number,
       format_code
from   (select title_code,
               product_number,
               format_code,
               max(case when format_code = 'OC' then 1 else 0 end) over (partition by title_code) oc,
               max(case when format_code = 'PB' then 1 else 0 end) over (partition by title_code) pb,
               max(case when format_code = 'HB' then 1 else 0 end) over (partition by title_code) hb
        from   sample_data)
where  oc = 1
and    pb = 0
and    hb = 0;

TITLE_CODE PRODUCT_NUMBER FORMAT_CODE
---------- -------------- -----------
      3456 C1             OC         
      7890 D1             OC         
      7890 D2             TD  

N.B。我添加了其中一个title_codes的format_code不是OC,HB和PB的情况;根据您要显示的内容,您可能需要添加and format_code = 'OC'的附加where子句。如果有两行格式为OC的行,您也无法说出您想要显示的内容......

相关问题