如何使用 MySQL 交叉聯接來對上一行值與當前行進行求和,並在另一行中顯示結果?
我們首先建立一個表 −
mysql> create table DemoTable(Value int); Query OK, 0 rows affected (1.79 sec)
使用 insert 命令向表中插入一些記錄 −
mysql> insert into DemoTable values(50); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.68 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.18 sec)
使用 select 語句從表中顯示所有記錄 −
mysql> select *from DemoTable;
這將產生以下輸出 −
+-------+ | Value | +-------+ | 50 | | 20 | | 30 | +-------+ 3 rows in set (0.00 sec)
以下是 MySQL 中對上一行求和的查詢 −
mysql> select t.Value, (@s := @s + t.Value) as Number from DemoTable t cross join (select @s := 0) p order by t.Value;
這將產生以下輸出 −
+-------+--------+ | Value | Number | +-------+--------+ | 20 | 20 | | 30 | 50 | | 50 | 100 | +-------+--------+ 3 rows in set (0.07 sec)
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP