下面是2个表中的示例记录
人员表
Per_Id + Per_type
--------------------------------------------
000001 SINGULAR
000002 COLLECTIVE
000003 INSTITUTION
000004 INSTITUTION
000005 SINGULAR
人员字符表
Per_Id + Char_Type + Char_Val
-------------------------------------------------------------------------------
000002 STAT_TY SUSPENSION
000002 STAT COMPLETE
000003 STAT_TY SUSPENSION
000003 STAT COMPLETE
000004 STAT_TY CESSATION
000004 STAT COMPLETE
000005 STAT_TY DEATH
000005 STAT PENDING
要求是我需要选择具有以下条件的人员
在上表中,查询返回的人员ID是
000001 (No record in char table)
000005 (The value of STAT char is not COMPLETE)
000003 (Institution person and char value is SUSPENSION)
下面是查询,在该查询中我需要帮助子句来选择满足第3点的记录。
SELECT P.PER_ID,
C.CHAR_VAL, C1.CHAR_VAL
FROM PERSON_TBL P
LEFT OUTER JOIN CHAR_TBL C ON C.PER_ID = P.PER_ID AND C.CHAR_TYPE = 'STAT_TY'
LEFT OUTER JOIN CHAR_TBL C1 ON C1.PER_ID = P.PER_ID AND C1.CHAR_TYPE = 'STAT'
WHERE
1=1
AND NVL(C.CHAR_VAL,' ') NOT IN ('CESSATION','DEATH')
AND NVL(STCS.SRCH_CHAR_VAL,' ') NOT IN ('COMPLETE')
AND ***need clause for selecting person of type SINGULAR and with char SUSPENSION***
答案 0 :(得分:1)
exists
和not exists
怎么样:
select p.*
from person_tbl p
where not exists (select 1
from person_char pc
where pc.per_id = p.per_id
) or
exists (select 1
from person_char pc
where pc.per_id = p.per_id and
pc.char_type = 'STAT' and
pc.char_value <> 'COMPLETE'
) or
(p.per_type = 'INSTITUTION' and
exists (select 1
from person_char pc
where pc.per_id = p.per_id and
pc.char_type = 'STAT_TY' and
pc.char_value = 'SUSPENSION'
)
);