美文网首页
MySQL 生成累计乘积

MySQL 生成累计乘积

作者: 只是甲 | 来源:发表于2020-10-23 14:15 被阅读0次

    备注:测试数据库版本为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)
    

    相关文章

      网友评论

          本文标题:MySQL 生成累计乘积

          本文链接:https://www.haomeiwen.com/subject/ymhwpktx.html