mysql累加、累减
程序员文章站
2022-04-14 16:45:34
累加 先上表结构: CREATE TABLE `abc` ( `jidu` int(11) NOT NULL AUTO_INCREMENT, `jine` int(11) DEFAULT NULL, PRIMARY KEY (`jidu`) ) ENGINE=InnoDB AUTO_INCREMEN ......
累加
先上表结构:
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;
完事,如有不对的地方请指正。
上一篇: mysql第八课