要在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中文網其他相關文章!