我想在Oracle Express的SQL中使用子查询来获取员工在其部门中获得的最高薪水的salary_id。我有的表是:
Employee
Emp_id Salary Dept_id
100 1000 a101
200 2000 a101
300 2500 b102
Salary
Grade LowSal HiSal
1 500 900
2 901 2000
3 2001 3000
首先,我使用此查询提取每个部门的最高工资:
SELECT Max(e.SALARY)
FROM EMPLOYEE e
GROUP BY e.DEPT_ID
结果有两个记录:2000和2500
下一步是获得这些工资的等级,所以我使用以下内容:
SELECT GRADE
FROM SALARY
WHERE (SELECT Max(e.SALARY)
FROM EMPLOYEE e
GROUP BY e.DEPT_ID) BETWEEN LOWSAL AND HIGHSAL;
我收到的错误是:ORA-01427:单行子查询返回多行
如何在SQL中使用子查询执行SQL命令?
答案 0 :(得分:1)
有多种方法可以编写此类查询。您可以将子查询添加到FROM
子句:
SELECT grade
FROM (SELECT max(salary) AS sal FROM employee GROUP BY dept_id) ms
JOIN salary ON ms.sal BETWEEN salary.lowsal AND salary.hisal;
或者您可以使用相关子查询:
SELECT (SELECT grade FROM salary WHERE max(salary) BETWEEN lowsal AND hisal)
FROM employee
GROUP BY dept_id
相关子查询通常较慢,因此首选表单。