让我们说这是我的员工表:员工(id,name,job,sal)。工作可能是"会计师","经理","职员"我尝试使用子查询获得每个作业类型的最高薪水,类似于此输出:
JOB NAME SALARY
clerk Bob 120
accountant Mike 320
manager Sam 660
SQL我试过:
SELECT
job,
ename,
sal
FROM
emp
WHERE
sal = (SELECT MAX(sal) FROM emp where job IN (SELECT DISTINCT(job) FROM emp));
我一直在尝试使用DISTINCT和MAX功能,但是我已经卡住了,可以在附近找不到任何帮助吗?
答案 0 :(得分:4)
如果你只需要每个工作的最高工资,那么这应该有效。
SELECT Max(SALARY) AS maxsalary,
JOB
FROM employee
GROUP BY JOB
如果你需要谁获得每个工作的最高工资,那就试试吧。
SELECT t1.JOB,
t1.NAME,
t1.SALARY
FROM employee t1
INNER JOIN (SELECT Max(SALARY) AS maxsalary,
JOB
FROM employee
GROUP BY JOB) t2
ON t1.JOB = t2.JOB
AND t1.SALARY = t2.maxsalary
答案 1 :(得分:0)
好的找出了一个看起来比上述更简单的答案:
SELECT job, name, salary
FROM employee
WHERE (salary, job) IN (SELECT MAX(salary), job FROM employee GROUP BY job);
感谢您的帮助