要在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 −> );
借助select语句在表中插入一些记录。插入记录的查询如下-
mysql> insert into CumulativeSumDemo values(101,400); mysql> insert into CumulativeSumDemo values(102,500); mysql> insert into CumulativeSumDemo values(103,600); mysql> insert into CumulativeSumDemo values(104,1000);
显示所有在插入命令帮助下插入的记录。查询如下-
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;
实现开头讨论的上述语法,以添加累积和列。查询如下-
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)