如何在 MySQL 中创建累计总和列?
mysqlmysqli database
要在 MySQL 中创建累计总和列,您需要创建一个变量并将其值设置为 0。累计总和会使用当前值逐步增加下一个值。
首先,您需要借助 SET 创建一个变量。语法如下 −
set @anyVariableName:= 0;
在 MySQL 中创建累计总和列的语法如下 −
select yourColumnName1,yourColumnName2,........N,(@anyVariableName := @anyVariableName + yourColumnName2) as anyVariableName from yourTableName order by yourColumnName1;
为了理解上述概念,让我们创建一个表。以下是创建表的查询−
mysql> create table CumulativeSumDemo −> ( −> BookId int, −> BookPrice int −> ); Query OK, 0 rows affected (0.67 sec)
使用 insert 语句在表中插入一些记录。插入记录的查询如下 −
mysql> insert into CumulativeSumDemo values(101,400); Query OK, 1 row affected (0.15 sec) mysql> insert into CumulativeSumDemo values(102,500); Query OK, 1 row affected (0.16 sec) mysql> insert into CumulativeSumDemo values(103,600); Query OK, 1 row affected (0.16 sec) mysql> insert into CumulativeSumDemo values(104,1000); Query OK, 1 row affected (0.18 sec)
显示我使用 insert 命令插入的所有记录。查询如下 −
mysql> select *from CumulativeSumDemo;
以下是输出 −
+--------+-----------+ | BookId | BookPrice | +--------+-----------+ | 101 | 400 | | 102 | 500 | | 103 | 600 | | 104 | 1000 | +--------+-----------+ 4 rows in set (0.00 sec)
要添加累计总和列,首先需要创建一个变量。查询如下 −
mysql> set @CumulativeSum := 0; Query OK, 0 rows impacted (0.00 sec)
实现开头讨论的上述语法以添加累计总和列。查询如下 −
mysql> select BookId,BookPrice,(@CumulativeSum := @CumulativeSum + BookPrice) as CumSum −> from CumulativeSumDemo order by BookId;
以下是输出。这里也可以看到累计总和列 −
+--------+-----------+--------+ | BookId | BookPrice | CumSum | +--------+-----------+--------+ | 101 | 400 | 400 | | 102 | 500 | 900 | | 103 | 600 | 1500 | | 104 | 1000 | 2500 | +--------+-----------+--------+ 4 rows in set (0.00 sec)