题目来源自, 牛客网数据库实战之获取所有部门中当前员工薪水最高的相关信息
给出dept_no, emp_no以及其对应的salary
初始化语句
CREATE TABLE `dept_emp` (
`emp_no` int(11) NOT NULL,
`dept_no` char(4) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`dept_no`));
CREATE TABLE `salaries` (
`emp_no` int(11) NOT NULL,
`salary` int(11) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`from_date`));
正确输出描述
方法1(错误):
select
d.dept_no,d.emp_no,max(s.salary) as salary
from dept_emp d,salaries s
where
d.emp_no=s.emp_no and
d.to_date=s.to_date
group by d.dept_no
结果
这里的emp_no和salary并不对应
GROUP BY 默认取非聚合的第一条记录!!!!!!
方法2(正确):
select
d.dept_no,d.emp_no,s.salary
from
dept_emp d,salaries s
where
d.emp_no=s.emp_no and
d.to_date=s.to_date and
s.salary=(
select
max(s2.salary)
from dept_emp d2 , salaries s2
where
d2.emp_no = s2.emp_no and
d2.to_date = s2.to_date and
d.dept_no=d2.dept_no
group by d2.dept_no
)
order by d.dept_no
结果
扫描二维码关注公众号,回复:
4440481 查看本文章