0

我被困在这里做作业,这就是我所得到的。

指令是:显示部门名称、城市和每个部门不同职位的数量。表员工(有job_id和department_id)、deptos(有location_id、department_id但没有job id)、位置(有location_id和city)我需要包括所有城市,即使是没有员工的城市

我试图做的...

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
4

3 回答 3

2

位置可能在其他表中缺少数据,因此右连接或从它开始并使用左连接。您还需要按城市分组。试图对 OP 查询进行最小的更改。

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

于 2013-10-09T16:24:46.300 回答
1

您需要使用 OUTER JOIN 来完成此操作......如下所示。您不一定必须使用隐含的关键字外部,只需记住使用 LEFT 和 RIGHT 连接之间的区别,这里有一篇文章。下面的例子

SQL Server 中的 LEFT JOIN 与 LEFT OUTER JOIN

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
于 2013-10-09T15:50:42.933 回答
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
于 2013-10-09T15:43:58.687 回答