ORACLE查询,如果一行满足FK条件,则忽略所有行

时间:2018-06-28 05:14:12

标签: sql oracle

我有一张数据如下的表。 我的要求是,如果FK具有类别M,则忽略FK的所有行。查询应仅返回类别为N且类型为Z的那些行。 同样,FK也被表示为(在(A,B)中) 基本上在下面的示例中,我需要将输出作为PK 5的行。

UPDATE "atul_sso"."ATL_SSO_ACCESS_REQ_DETAILS"@"mysql_atulsso.atul.co.in"
SET "atul_sso"."ATL_SSO_ACCESS_REQ_DETAILS"."REQ_TYPE"@"mysql_atulsso.atul.co.in"= 'r2' 
WHERE "atul_sso"."ATL_SSO_ACCESS_REQ_DETAILS"."REQ_TYPE"@"mysql_atulsso.atul.co.in"='r1';

谢谢

5 个答案:

答案 0 :(得分:1)

为什么不尝试

   SELECT *
  FROM tab_name
 WHERE     UPPER (category) = 'N'
       AND UPPER (type) = 'Z'
       AND UPPER (fk) IN ('A', 'B')

SQL Fiddle

WITH t
     AS (SELECT 1 AS pk,
                'A' AS fk,
                'L' AS category,
                'X' AS TYPE
           FROM DUAL
         UNION
         SELECT 2 AS pk,
                'A' AS fk,
                'M' AS category,
                'Y' AS TYPE
           FROM DUAL
         UNION
         SELECT 3 AS pk,
                'A' AS fk,
                'N' AS category,
                'Z' AS TYPE
           FROM DUAL
         UNION
         SELECT 4 AS pk,
                'B' AS fk,
                'L' AS category,
                'X' AS TYPE
           FROM DUAL
         UNION
         SELECT 5 AS pk,
                'B' AS fk,
                'N' AS category,
                'Z' AS TYPE
           FROM DUAL
         UNION
         SELECT 6 AS pk,
                'C' AS fk,
                'L' AS category,
                'X' AS TYPE
           FROM DUAL
         UNION
         SELECT 7 AS pk,
                'C' AS fk,
                'M' AS category,
                'Y' AS TYPE
           FROM DUAL
         UNION
         SELECT 8 AS pk,
                'C' AS fk,
                'N' AS category,
                'Z' AS TYPE
           FROM DUAL)
(SELECT distinct *
   FROM t
  WHERE     UPPER (category) = 'N'
        AND UPPER (TYPE) = 'Z'
        AND UPPER (fk) IN ('A', 'B'))

输出

╔════╦════╦══════════╦══════╗
║ PK ║ FK ║ CATEGORY ║ TYPE ║
╠════╬════╬══════════╬══════╣
║  3 ║ A  ║ N        ║ Z    ║
║  5 ║ B  ║ N        ║ Z    ║
╚════╩════╩══════════╩══════╝

答案 1 :(得分:0)

最简单但可能不是最有效的

SELECT * 
FROM tab_name
WHERE FK not in (SELECT FK FROM tab_name WHERE catergory='M')

答案 2 :(得分:0)

尝试一下。

 SELECT *
  FROM table_name
 WHERE Category = 'N' 
     AND Type = 'Z' 
     AND FK IN ('A', 'B');

答案 3 :(得分:0)

Try this

Select PK, FK, Category, Type
From tab_name
Where Category = Case when Category = 'M' Then 'N' else Category end
and Type = Case when Category = 'M' Then 'Z' else Type end
and FK in ('A', 'B')

答案 4 :(得分:0)

您似乎想要:

select t.*
from t
where t.category = 'N' and t.type = 'Z' and
      not exists (select 1 
                  from t t2
                  where t2.fk = t.fk and t2.category = 'M'
                 );

您还可以使用分析功能:

select t.*
from (select t.*,
             sum(case when category = 'M' then 1 else end) over (partition by fk) as m_cnt
      from t
     ) t
where category = 'N' and type = 'Z' and
      m_cnt = 0;