在多个数据行中使用Oracle SQL过滤行

时间:2015-09-03 08:48:22

标签: sql oracle

我的数据仅用于说明目的:

Record_ID | Product | Status
1         | Car     | Active
2         | Car     | Awesome
3         | Truck   | Active
4         | Truck   | Defect

我想生成如下查询结果:

Record_ID | Product |
1         | Car     |

卡车被排除在外,因为它在Record_ID 4中有缺陷信息

记录ID 2被排除,因为状态“活动”的加权超过状态“Awesome”

是否有机会使用单个Oracle Query返回结果?

谢谢!

2 个答案:

答案 0 :(得分:0)

使用以下查询

     select Record_ID,product from
        (
        select Record_ID, product ,row_number() over(partition by product order by Record_ID ) as r_no
        from ss
        where product not  in (select product from ss where status='Defect'))
        where R_no=1

答案 1 :(得分:0)

仅使用一次表扫描:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE Product_Statuses ( Record_ID, Product, Status ) AS
          SELECT 1, 'Car',      'Active'  FROM DUAL
UNION ALL SELECT 2, 'Car',      'Awesome' FROM DUAL
UNION ALL SELECT 3, 'Truck',    'Active'  FROM DUAL
UNION ALL SELECT 4, 'Truck',    'Defect'  FROM DUAL
UNION ALL SELECT 5, 'Airplane', 'Awesome' FROM DUAL

查询1

SELECT MIN( Record_ID ) KEEP ( DENSE_RANK FIRST ORDER BY DECODE( Status, 'Active', 1, 'Awesome', 2, 3 ) ) AS Record_ID,
       MIN( Status )    KEEP ( DENSE_RANK FIRST ORDER BY DECODE( Status, 'Active', 1, 'Awesome', 2, 3 ) ) AS Status
FROM   Product_Statuses
GROUP BY Product
HAVING SUM( DECODE( Status, 'Defect', 1, 0 ) ) = 0
ORDER BY RECORD_ID

<强> Results

| RECORD_ID |  STATUS |
|-----------|---------|
|         1 |  Active |
|         5 | Awesome |