方法一:
select
b.emp_no,
b.salary,
(select
sum(a.salary) running_total
from salaries a
where a.emp_no<=b.emp_no
and a.to_date = '9999-01-01'
)
from salaries b
where b.to_date = '9999-01-01'
本题可使用子查询,通过where a.emp_no<=b.emp_no、sum(a.salary)形成running_total的累计条件;
或直接使用sum(salary) over(order by emp_no) 形成running_total的累计条件。
方法二:
select
emp_no,
salary,
sum(salary) over(order by emp_no) as running_total
from salaries
where to_date='9999-01-01'
emp_no,
salary,
sum(salary) over(order by emp_no) as running_total
from salaries
where to_date='9999-01-01'
总结:
sum(…) over( ),对所有行求和
sum(…) over( order by … ), 连续求和
sum(…) over( partition by… ),同组内所行求和
sum(…) over( partition by… order by … ),同第1点中的排序求和原理,只是范围限制在组内
使用 sum(sal) over (order by id)… 查询员工的薪水“连续”求和,
注意over (order by id)如果没有order by 子句,求和就不是“连续”的
sum(sal) over (partition by bumen order by id) 按部门“连续”求总和
sum(sal) over (partition by bumen) 按部门求总和。
sum(…) over( ),对所有行求和
sum(…) over( order by … ), 连续求和
sum(…) over( partition by… ),同组内所行求和
sum(…) over( partition by… order by … ),同第1点中的排序求和原理,只是范围限制在组内
使用 sum(sal) over (order by id)… 查询员工的薪水“连续”求和,
注意over (order by id)如果没有order by 子句,求和就不是“连续”的
sum(sal) over (partition by bumen order by id) 按部门“连续”求总和
sum(sal) over (partition by bumen) 按部门求总和。