0

I am stuck here working on a homework and this is what I have got.

Instruction is: Display department name, city and number of different jobs in each department. tables employees (has job_id and department_id), deptos (has location_id, department_id but no job ids), locations (has location_id and city) I need to include all cities even the ones without employees

What I was trying to do...

select d.department_name, l.city, count (distinct e.job_id)
from employees e
join deptos d on (e.department_id=d.department_id)
join locations l on (d.location_id=l.location_id)
group by d.department_name
PhillToronto
  • 93
  • 1
  • 2
  • 13

3 Answers3

2

locations can have data missing in other tables, so right join or you start from it and use left joins. You also need to group by city. Tried to do minimum changes to OP query.

select d.department_name, l.city, count(distinct e.job_id)
from employees e
join deptos d on (e.department_id=d.department_id)
right join locations l on (d.location_id=l.location_id)
group by d.department_name, l.city

SQL Fiddle to test with

Elhana
  • 309
  • 3
  • 9
1

You need to use a OUTER JOIN to accomplish this... like the below. You do not necessarily have to use the keyword outer as it is implied, just remember the the difference between using LEFT and RIGHT joins there is a post on that here. Example below

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

select d.department_name, l.city, count (distinct e.job_id)
from locations l
left outer join deptos d on (e.department_id=d.department_id)
left outer join employees e on (d.location_id=l.location_id)
group by d.department_name
Community
  • 1
  • 1
Jwit
  • 156
  • 6
0
SELECT locations.city, deptos.department_name, 
       Count(DISTINCT employees.job_id) AS DiffJobsDeptCount
FROM employees 
     RIGHT JOIN (deptos 
     RIGHT JOIN locations 
     ON deptos.location_id = locations.location_id) 
     ON employees.department_id  = deptos.department_id
GROUP BY locations.city, deptos.department_name
Linger
  • 14,942
  • 23
  • 52
  • 79