要在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)
借助select语句向表中插入一些记录。插入记录的查询如下 -
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)
显示我借助插入命令插入的所有记录。查询如下 -
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 affected (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)
以上是如何在 MySQL 中创建累积和列?的详细内容。更多信息请关注PHP中文网其他相关文章!