加入3个表和组

时间:2013-10-09 15:32:21

标签: sql oracle join oracle11g oracle-sqldeveloper

我被困在这里从事家庭作业,这就是我所拥有的。

说明是:显示各部门的部门名称,城市和不同工作的数量。 表employees(有job_id和department_id),deptos(有location_id,department_id但没有工作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

3 个答案:

答案 0 :(得分: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 to test with

答案 1 :(得分:1)

您需要使用OUTER JOIN来完成此操作......如下所示。你不一定要使用暗示的关键字outer,只记得使用LEFT和RIGHT联接之间的区别,这里有一个帖子。以下示例

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

答案 2 :(得分: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