如何在简单的oracle查询中使用'EXIST'

时间:2013-10-17 10:12:28

标签: oracle

我有一个名为'MainTable'的表,其中包含以下数据 enter image description here

另一个名为'ChildTable'的表,其中包含以下数据(foreighn key Number)
enter image description here

现在我想从'ChildTable'获取那些记录,如果至少存在一个'S'状态。 但如果此号码的任何其他记录为“R”,那么我不想获取它 像这样的东西 - enter image description here

我试过了

Select m.Number, c.Status from MainTable m, ChildTable c
where EXISTS (SELECT NULL                                 
              FROM ChildTable c2                      
              WHERE  c2.status =’S’ and c2.status <> ‘R’                           
              AND  c2.number = m.number)

但是在这里我的记录也有“R”状态,我做错了什么?

3 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情

select num, status
from
(select id,  num, status,
sum(decode(status, 'R', 1, 0)) over (partition by num) Rs,
sum(decode(status, 'S', 1, 0)) over (partition by num) Ss
from child_table) t
where t.Rs = 0 and t.Ss >= 1
-- and status = 'S'

Here is a sqlfiddle demo

答案 1 :(得分:1)

带有'R'的子记录可能与维护记录相关联,该记录还有另一个状态为'S'的子记录 - 这就是您的查询所要求的。

Select
  m.Number,
  c.Status
from MainTable m
join ChildTable c on c.number = m.number
where EXISTS (
        SELECT NULL                                 
        FROM   ChildTable c2                      
        WHERE  c2.status =’S’                         
          AND  c2.number = m.number) and
      NOT EXISTS (
        SELECT NULL                                 
        FROM   ChildTable c2                      
        WHERE  c2.status =’R’                         
          AND  c2.number = m.number)

答案 2 :(得分:0)

WITH ChildrenWithS AS (
    SELECT Number
    FROM ChildTable
    WHERE Status = 'S'
)
,ChildrenWithR AS (
    SELECT Number
    FROM ChildTable
    WHERE Status = 'R'
)
SELECT MaintTable.Number
      ,ChildTable.Status
FROM MainTable
     INNER JOIN ChildTable
         ON MainTable.Number = ChildTable.Number
WHERE MainTable.Number IN (SELECT Number FROM ChildrenWithS)
      AND MainTable.Number NOT IN (SELECT Number FROM ChildrenWithR)