MySQL 中選擇累加 (流動總計) 列?


要選擇累加列,我們首先建立一個演示表。建立表的查詢如下 −

mysql> create table accumulatedDemo
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.58 sec)

使用插入命令在表中插入一些記錄。查詢如下 −

mysql> insert into accumulatedDemo values(10);
Query OK, 1 row affected (0.21 sec)
mysql> insert into accumulatedDemo values(15);
Query OK, 1 row affected (0.09 sec)
mysql> insert into accumulatedDemo values(20);
Query OK, 1 row affected (0.13 sec)
mysql> insert into accumulatedDemo values(25);
Query OK, 1 row affected (0.12 sec)
mysql> insert into accumulatedDemo values(45);
Query OK, 1 row affected (0.14 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下 −

mysql> select *from accumulatedDemo;

以下為輸出 −

+-------+
| Value |
+-------+
| 10    |
| 15    |
| 20    |
| 25    |
| 45    |
+-------+
5 rows in set (0.00 sec)

以下是選擇累加列的查詢 −

mysql> set @previousSum =0;
Query OK, 0 rows affected (0.00 sec)
mysql> select Value, @previousSum: =@previousSum+ Value AS AccumulatedColumn from accumulatedDemo;

以下為輸出 −

+-------+-------------------+
| Value | AccumulatedColumn |
+-------+-------------------+
| 10    | 10                |
| 15    | 25                |
| 20    | 45                |
| 25    | 70                |
| 45    | 115               |
+-------+-------------------+
5 rows in set (0.00 sec)

更新日期: 2019 年 7 月 30 日

218 次瀏覽

開啟你的職業道路

完成課程獲得認證

開始
廣告
© . All rights reserved.