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.