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.

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)

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:

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:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement