题目描述:按照salary的累计和running_total,其中running_total为前N个当前( to_date = '9999-01-01')员工的salary累计和,其他以此类推。

窗口函数(最简单的写法):

select emp_no,
    salary,
    sum(salary) over(order by emp_no) as running_total
from salaries
where to_date="9999-01-01"

直接用sum()窗口函数按照emp_no的升序累加salary就好。

自联结(里面的逻辑有点绕):

select t1.emp_no, t1.salary, sum(t2.salary) as running_total
from salaries t1 join salaries t2 
               on t1.emp_no >= t2.emp_no
where t1.to_date="9999-01-01" and t2.to_date="9999-01-01"
group by t1.emp_no

重点:t1.emp_no>=t2.emp_no,因为我这里是sum(t2.salary).所以结合起来看就是查找小于等于t1.emp_no的t2.salary总和。
例如:
t1| t2
10001 88958| 10001 88958
10002 72527| 10002 72527
10003 43311| 10003 43311
10004 74057| 10004 74057
当t1.emp_no=10001时,t2.emp_no<=10001的只有10001,所以running_total为88958.
当t1.emp_no=10002时,t2.emp_no<=10002的有10001,10002,所以running_total为88958+72527
......
另外这种方法要对t1,t2的to_date都限制为当前薪水"9999-01-01-01"
另一种写法:

select t1.emp_no, t1.salary, sum(t2.salary) as running_total
from salaries t1, salaries t2
where t1.emp_no >= t2.emp_no 
  and t1.to_date="9999-01-01" 
  and t2.to_date="9999-01-01"
group by t1.emp_no,t1.salary