如何在MySQL中创建累积和列?
要在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)
显示我使用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 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)
广告