Chen
Chen

Reputation: 383

Left join or inner join

I have a table, Table_employee has employee ID, salary, manager(the ID of each employee's respective manager), and another table Table_manager which has each manager's first name, last name, and each manager's ID.

I was trying to create another table presenting manager's first name, last name, and count of employees each manager is responsible for and the total salary of those employees.

I am having trouble to have manager's first name and last name present.

My code is as below. Any helps would be highly appreciated.

Thank you very much!

select 
   e.manager, 
   COUNT(e.employee_id), 
   SUM(e.salary) 
FROM 
   Table_employee e 
   Right outer join Table_manager m ON e.manager=m.employee_id 
GROUP BY 
   manager 
ORDER BY 
   manager

Upvotes: 0

Views: 82

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

Use a LEFT JOIN and aggregation. If you are learning SQL, just forget RIGHT JOIN. It is almost never needed. And LEFT JOIN is easier to follow ("keep everything in the first table" versus "keep everything in the last table, whatever that might be").

So:

select m.employee_id, m.firstname, m.lastname, 
       count(e.employee_id), sum(e.salary)
from Table_manager m left join
     Table_employee e
     ON e.manager = m.employee_id
group by m.employee_id, m.firstname, m.lastname
order by m.employee_id;

Upvotes: 2

binderbound
binderbound

Reputation: 799

You just need to add firstname and lastname to group by I think? Am I missing some complexity?

select e.manager, m.firstname, m.lastname, COUNT(e.employee_id), SUM(e.salary)
FROM Table_employee e
Right outer join Table_manager m ON e.manager=m.employee_id\
GROUP BY manager, m.firstname, m.lastname
ORDER BY manager

However, swapping order so that manager is on left and employee on right makes more sense, so that you don't miss managers without employees:

select e.manager, m.firstname, m.lastname, COUNT(e.employee_id), SUM(e.salary)
FROM Table_manager m
Right outer join Table_employee e ON e.manager=m.employee_id
GROUP BY manager, m.firstname, m.lastname
ORDER BY manager

Upvotes: 1

Related Questions