Skip to content
Advertisement

How to exclude entire Customer ID data based on a condition

I need to exclude all data relating to Customer ID’s that have at least one instance where a condition applies. For instance:

This is all my data with conditions

+-------------+----------------+
| Customer ID |   Condition    |  
+-------------+----------------+
|           1 | Contacted      |  
|           1 | No Answer      |  
|           1 | Left Voicemail | 
|           1 | Spoke to       |  
|           2 | No Answer      |  
|           2 | Left Voicemail |  
|           3 | Spoke to       |  
|           3 | No Answer      |  
|           4 | Contacted      |  
|           4 | Left Voicemail |  
+-------------+----------------+

I need to exclude data with conditions equal to ‘Contacted’. Currently, I am using the below code and getting the following results:

SELECT a.customerID, 
       c.condition
  FROM Tablea a
  JOIN Tablec c ON
  c.customerID = a.customerID
  WHERE c.condition NOT LIKE 'Contacted'
+-------------+----------------+
| Customer ID |   Condition    |  
+-------------+----------------+ 
|           1 | No Answer      |  
|           1 | Left Voicemail | 
|           1 | Spoke to       |  
|           2 | No Answer      |  
|           2 | Left Voicemail |  
|           3 | Spoke to       |  
|           3 | No Answer      |    
|           4 | Left Voicemail |  
+-------------+----------------+

However, I would like to exclude all of the Customer ID rows if the Customer ID has the condition. Ideally the code would produce the following:

+-------------+----------------+
| Customer ID |   Condition    |  
+-------------+----------------+ 
|           2 | No Answer      |  
|           2 | Left Voicemail |  
|           3 | Spoke to       |  
|           3 | No Answer      |  
+-------------+----------------+

Any help is greatly appreciated!

Advertisement

Answer

This will get you the results you are looking for:

Select customerid, condition from
Tablec c
WHERE customerid NOT IN
(
   Select customerid from
   Tablec
   WHERE condition LIKE 'Contacted'
)

In your above example I am uncertain as to why you are joining to Tablea, as you aren’t pulling any data from that table except for customerID, which is already in Tablec.

However if you wanted to do the join, you could do:

Select a.customerID, c.condition from Tablea a
JOIN Tablec c ON c.customerID = a.customerID
WHERE c.customerid NOT IN
(
   Select customerid from
   Tablec 
   WHERE condition LIKE 'Contacted'
)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement