Skip to content
Advertisement

Compare records in same table using self join

I am looking to get Permanent employee who has joining date greater than manager.

WITH Employee AS(
        SELECT *
        FROM (VALUES(1, 'O1',   'Manager',      'Emp1', 2015),
                    (2, 'O1',   'Permanent',    'Emp2', 2016),
                    (3, 'O1',   'Contractor',   'Emp3', 2016),
                    (4, 'O2',   'Contractor',   'Emp4', 2015),
                    (5, 'O1',   'Permanent',    'Emp5', 2014),
                    (6, 'O1',   'Contractor',   'Emp6', 2013),
                    (7, 'O2',   'Permanent',    'Emp7', 2017),
                    (8, 'O1',   'Manager',      'Emp8', 2017),
                    (9, 'O2',   'Permanent',    'Emp9', 2019))
                    V(id, Organisation, type,Name, yearOfJoing))

This is what I tried till now, but I get zero records. I am expecting ouptut as Epmoyee with Id 9 as it has joining year(2019) greater than both the managers(2017 and 2015)

  select * from Employee M JOIN Employee P 
    ON M.id = P.id 
    AND M.type ='Manager' AND P.type ='Permanent'
    WHERE p.yearOfJoing > M.yearOfJoing

Advertisement

Answer

The join condition on id is the problem; this is the primary key of your table, so you end up looking for a single record that has different types and dates.

I think that this would be simpler expressed with a lateral join:

select e.*, m.id managerId, m.name mamagerName, m.yearOfJoining managerYearOfJoining
from employee e
cross apply (
    select m.*
    from employee m
    where 
        m.organisation = e.organisation 
        and m.type = 'Manager' 
        and m.yearOfJoining < e.yearOfJoining
) m
where e.type = 'Permanent'

Demo on DB Fiddle:

id | Organisation | type      | Name | yearOfJoining | mamagerName | managerYearOfJoining
-: | :----------- | :-------- | :--- | ------------: | :---------- | -------------------:
 2 | O1           | Permanent | Emp2 |          2016 | Emp1        |                 2015

This checks the date of joining of the employee agains the manager of the same organisation. On the other hand, if you want employees that joined after any manager:

select e.*
from employee e
where 
    e.type = 'Permanent'
    and not exists (
        select 1 
        from employee m
        where m.type = 'Manager' and m.yearOfJoining >= e.yearOfJoining
    )
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement