要在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 中創建累積和列?的詳細內容,更多請關注www.92cms.cn其它相關文章!