一个糟糕的数据库设计的例子,由于数据库设计得不合理把此类逻辑人为的变得复杂了:
select
t3.dept_no,
t3.emp_no,
t7.max_salary
from
(
select
t1.dept_no,
t2.emp_no,
t2.salary
from
dept_emp t1
left join salaries t2 on t1.emp_no = t2.emp_no
where
t1.to_date = '9999-01-01'
) t3
inner join (
select
dept_no,
max(salary) max_salary
from
(
select
t4.dept_no,
t4.emp_no,
t5.salary
from
dept_emp t4
left join salaries t5
on t4.emp_no = t5.emp_no
where
t4.to_date = '9999-01-01'
) t6
group by
1
) t7
on t3.dept_no = t7.dept_no
and t3.salary = t7.max_salary
order by
t3.dept_no;
在OLAP中,将join的逻辑提炼出来,以上的sql就很明晰了:
create table current_employee
as select
t1.dept_no,
t2.emp_no,
t2.salary
from
dept_emp t1
left join salaries t2 on t1.emp_no = t2.emp_no
where
t1.to_date = '9999-01-01';
再将这段逻辑替换到最上面的答案中去,就比较明朗了。