简体   繁体   中英

How to join two tables where IDs from 1st one mustn't be included in 2nd one but they're the key

I have the following issue. I have to get all the records for customers who hasn't signed a deal and then 2 months later they don't have contracts as well. Meanwhile some of them has signed a contract.

I have these columns:

CUSTOMER_ID DATE        CONTRACT_NO
123         2016-03-05  4433666
234         2016-03-08  6633666
456         2016-03-17  1224633
456         2016-03-11  NULL
875         2016-03-10  2466443
875         2016-03-06  NULL
422         2016-03-21  4433555

Could you tell me what can I do?

I'm using Oracle.

customers who hasn't signed a deal and then 2 months later they don't have contracts as well.

In other words - for a given record check whether in 2 next months there is no any records with the same clientId and not null contract_no.

SELECT * FROM table t
WHERE NOT EXISTS (
   SELECT 1 FROM table t1
   WHERE t.CUSTOMER_ID = t1.CUSTOMER_ID
     AND t1.DATE > t.DATE 
     AND t1.DATE <= t.DATE + interval '2' month
     AND t1.CONTRACT_NO IS NOT NULL
)

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