简体   繁体   中英

How to fetch rows by comparing to multiple records at same time in oracle sql

ba_no        account          ba_no    key_id        key_id    child_id   expiration_date   sysdate
x-------------------x        -------------------      ------------------------------------------------    
100            1              100         23            23         1001      28-apr-20        sysdate
100            1              101         24            23         1002      28-apr-21        sysdate
101            2              102         25            23         1003      28-apr-20        sysdate
102            3                                        24         2000      28-apr-20        sysdate
                                                        24         2052      28-apr-20        sysdate
                                                        25         5201      28-apr-20        sysdate
       A                            B                                     C

I have 3 tables I want to fetch all records from table A whose all childs(child_id) in table C are expired (expiration_date<sydate) by taking join in such a way that ba_no is common in A & B and key_id is common in B & C.

You can use not exists :

select a.*
from a
where not exists (select 1
                  from b join
                       c
                       on b.key_id = c.key_id
                  where b.ba_no = a.ba_no and
                        c.expiration_date >= trunc(sysdate)
                 );

Note that this uses trunc(sysdate) because sysdate has a time component.

One option would be comparing distinctly counted child_id versus number of expired records in order to determine key_id values within the subquery, and then use these value to match the join of A and B tables to get the related values of table A :

SELECT A.*
  FROM A
  JOIN B 
    ON B.ba_no = A.ba_no
  JOIN  
  (
   SELECT C.key_id
     FROM B
     JOIN C
       ON C.key_id = B.key_id
    GROUP BY C.key_id
   HAVING COUNT(DISTINCT C.child_id) = 
          SUM(CASE WHEN C.expiration_date < TRUNC(sysdate) THEN 1 ELSE 0 END)) BC
    ON BC.key_id = B.key_id

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM