• mysql累加、累减


    累加

    先上表结构:

    CREATE TABLE `abc` (
      `jidu` int(11) NOT NULL AUTO_INCREMENT,
      `jine` int(11) DEFAULT NULL,
      PRIMARY KEY (`jidu`)
    ) ENGINE=InnoDB AUTO_INCREMENT=14270 DEFAULT CHARSET=utf8;

    数据:

    INSERT INTO `abc` (`jidu`, `jine`) VALUES ('1', '100');
    INSERT INTO `abc` (`jidu`, `jine`) VALUES ('2', '200');
    INSERT INTO `abc` (`jidu`, `jine`) VALUES ('3', '300');
    INSERT INTO `abc` (`jidu`, `jine`) VALUES ('4', '300');

    想要的结果为季度金额的累加值:

    这里利用错位自关联来实现,先看关联效果

    select * from abc a JOIN abc b ON a.jidu >= b.jidu;

     下面就好办了,实现语句为:

    select a.jidu,a.jine,sum(b.jine) as leiji
    from abc a JOIN abc b ON a.jidu >= b.jidu 
    GROUP BY a.jidu ORDER BY jidu;

    累减

    还是上面那个表,要的结果为每季度的金额差额:

     还是自关联,先看关联效果:

    select * from abc a left JOIN abc b ON a.jidu = b.jidu+1 ORDER BY a.jidu;

     实现的sql:

    select a.jidu,a.jine,ifnull(a.jine-b.jine,a.jine) as cha 
    from abc a left JOIN abc b ON a.jidu = b.jidu+1 ORDER BY a.jidu;

    完事,如有不对的地方请指正。

  • 相关阅读:
    PID 不能控制哪些系统?
    矩阵正定、负定、半正定、半负定
    KKT条件(不等式约束优化)
    腾讯OCR身份证正面识别
    小程序
    tomcat相关
    linux安装tomcat
    linux防火墙
    nginx操作
    Clean Code
  • 原文地址:https://www.cnblogs.com/wangb2/p/12125334.html
Copyright © 2020-2023  润新知