備註:測試數據庫版本爲MySQL 8.0
如需要scott用戶下建表及錄入數據語句,可參考:
scott建表及錄入數據sql腳本
一.需求
計算某給數字列的累乘積。其操作方式與“計算累計和”相似,只是使用乘法而不是加法。
二.解決方案
作爲例子,本解決方案中都計算職員工資的累成績。雖然工資的累成績沒有多大用處,然而可以很容易地把該技巧用於其它更有用的領域。
select e.empno,e.ename,e.sal,
( select round(exp(sum(ln(d.sal))))
from emp d
where d.empno <= e.empno
and e.deptno = d.deptno) as running_prod
from emp e
where e.deptno = 10
運行記錄:
mysql> select e.empno,e.ename,e.sal,
-> ( select round(exp(sum(ln(d.sal))))
-> from emp d
-> where d.empno <= e.empno
-> and e.deptno = d.deptno) as running_prod
-> from emp e
-> where e.deptno = 10;
+-------+--------+---------+--------------+
| empno | ename | sal | running_prod |
+-------+--------+---------+--------------+
| 7782 | CLARK | 2450.00 | 2450 |
| 7839 | KING | 5000.00 | 12250000 |
| 7934 | MILLER | 1300.00 | 15925000000 |
+-------+--------+---------+--------------+
3 rows in set (0.00 sec)