Question

I'm having some difficulty with a one to many query in SQL server 2008, I have two tables (Table1 & Table2 - Create Table statements are below).

I'm trying to find all the Active records in Table2 that do not have an Active status in table1, the problem I'm having is that table1 can have multiple records for a single emp_id with both active & inactive status.

The objective here is that if you are active in table2 you must at least have one active record in table1, I don't care if you are inactive as well, just so long as you have at least one single active status, if not, I want to see who you are.

CREATE TABLE Table1
    ([Emp_ID] int, [Status] varchar(10), [code] varchar(10))
;

INSERT INTO Table1
    ([Emp_ID], [Status], [code])
VALUES
    (12345, 'active', 'red'),
    (12345, 'inactive', 'blue'),
    (88888, 'active', 'green'),
    (12345, 'active', 'green'),
    (54321, 'inactive', 'blue'),
    (54321, 'inactive', 'green')
;

CREATE TABLE Table2
    ([Emp_ID] int, [Status] varchar(10), [Alias] varchar(10))
;

INSERT INTO Table2
    ([Emp_ID], [Status], [alias])
VALUES
    (12345, 'active', 'smith'),
    (88888, 'active', 'Jones'),
    (54321, 'active', 'West')
;

I thought something like this but it's not returning any results, I should return emp_id = 54321 because they do not have a single active row in table1 but are active in table2.

select table2.* 
From table2
Inner Join Table1 
  On table2.emp_id = table1.emp_id
  Where Table2.status = 'Active'
  AND Not EXISTS (select * from table1 where table1.status = 'Active')

Thanks for any suggestions.

Was it helpful?

Solution 2

I don't think your inner join with table1 is doing anything. All that it would do is duplicate your results for table2. The validations you need are done with the EXISTS. And you should relate t2.emp_id with the EXISTS subquery:

select t2.* 
from table2 t2  
where t2.status = 'Active'
  and not exists (select 1 
                  from table1 tt
                  where tt.emp_id = t2.emp_id
                    and tt.status = 'Active')

sqlfiddle demo

This will give you the record that has no active status in table1:

EMP_ID  STATUS  ALIAS
54321   active  West

OTHER TIPS

Here's a working Example on SQLFiddle.com: http://sqlfiddle.com/#!3/bd302/8

SELECT T2.*
FROM Table2 T2 LEFT JOIN Table1 T1
    ON T2.Emp_ID = T1.Emp_ID AND T2.Status = T1.Status
WHERE T2.Status = 'Active' AND T1.Status IS NULL

Explanation: You have to do a LEFT JOIN from Table2 with Table1, and JOIN on Emp_ID and Status. That way, if you check for Condition WHERE Table2's Status is Active, but Table1 Status is NULL, it means that there are no 'Active' records present in Table1 for that Table2 Emp_ID.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top