Question

I have a table called employees that contains the columns.

ID | Name | Salary | Department_id | Boss_id

So all employees are listed in this no matter where they're bosses or not. If someone is not a boss then their value for Boss_id will be NULL.

The aim is, to figure out if any employees earn more than their respective bosses and by respective I mean, from the same department.

I've been working on this trying to figure it out and I'm not sure if I need a loop to loop through all the departments or if there is an easier way.

Was it helpful?

Solution 2

SELECT t1.ID, t1.Name 
FROM table1 t1 
INNER JOIN table2 t2
ON t1.ID = t2.Boss_id
AND t1.Salary > t2. Salary
AND t1.Department_id = t2.Department_id 

OTHER TIPS

No, you don't need a loop.

If you want to compare the salary of an employee to the salary of his "boss", you can use a JOIN operation.

To list only those employees that have a higher salary than their boss:

SELECT e.*
  FROM employee e
  JOIN employee b
    ON b.id = e.boss_id
   AND e.salary > b.salary

If you want to list all employees, and just add a column that indicates whether their salary is higher than their bosses salary, along with bosses salary:

SELECT e.*
     , IF(e.salary>b.salary,'Y','N') AS higher_salary_than_boss
     , b.salary AS boss_salary
  FROM employee e
  LEFT
  JOIN employee b
    ON b.id = e.boss_id
 ORDER
    BY e.id

I don't see how "department" really comes into play.

If you want to compare an employee's salary to of his bosses boss, you could add yet another LEFT JOIN to the employee table.

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