SQL子查询,带有group by和两个表的联接

时间:2018-12-14 21:29:49

标签: sql oracle join subquery aggregate

所以我有两个桌子 EMPLOYEE-包含列,包括EMPLOYEE_NAME,DEPARTMENT_ID和SALARY DEPARTMENTS-包含列,包括DEPARTMENT_NAME和DEPARTMENT_ID

我需要显示每个部门的部门名称和平均工资,并按平均工资对其进行排序。

我是DB的新手,遇到了麻烦。 我尝试在from字段中进行子查询(此子查询返回的正是我需要的值减去部门名称,然后我需要将部门表加入到结果中),子查询中的所有数据都在一个表employees中。而部门名称在“部门”表中。

这是我尝试过的。

SELECT D.DEPARTMENT_NAME, T.PERDEPT
  FROM
(
 SELECT DEPARTMENT_ID, AVG(SALARY) AS PERDEPT
 FROM EMPLOYEE
 GROUP BY DEPARTMENT_ID
 ORDER BY PERDEPT
) AS TEST T
JOIN DEPARTMENTS
ON D.DEPARTMENT_ID=T.DEPARTMENT_ID;

这将返回

  

SQL命令未正确终止

AS TEST T

非常感谢所有帮助 非常感谢

2 个答案:

答案 0 :(得分:0)

此查询应满足您的要求

select d.department_name, avg(e.salary) as avg_salary
from salary_department d
left join employee e on e.department_id = d.department_id
group by d.department_name
order by avg(e.salary)

答案 1 :(得分:0)

只需更正表别名,因为您似乎对子查询有两个别名( TEST T ),而对 D 没有赋值。为每个表/查询引用使用一个别名调整SQL:

...
(
 SELECT ...
) AS T
JOIN DEPARTMENTS D

话虽如此,假设 DEPARTMENT_ID DEPARTMENTS 表中唯一,您甚至不需要子查询,因为带有JOIN的聚合查询就足够了计算总数。

SELECT D.DEPARTMENT_NAME, 
       AVG(E.SALARY) AS PERDEPT
FROM EMPLOYEE E
JOIN DEPARTMENTS D
  ON E.DEPARTMENT_ID = D.DEPARTMENT_ID
GROUP BY E.DEPARTMENT_ID, 
         D.DEPARTMENT_NAME
ORDER BY AVG(SALARY)