以特定方式对单个 MySQL 列中的值进行求和?
mysqlmysqli database
使用聚合函数 SUM() 和 OVER。让我们首先创建一个表 −
mysql> create table DemoTable ( CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerValue int ); Query OK, 0 rows affected (0.64 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(CustomerValue) values(10); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(CustomerValue) values(20); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(CustomerValue) values(30); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(CustomerValue) values(40); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+------------+---------------+ | CustomerId | CustomerValue | +------------+---------------+ | 1 | 10 | | 2 | 20 | | 3 | 30 | | 4 | 40 | +------------+---------------+ 4 rows in set (0.00 sec)
以下是以特定方式对单个列中的值进行求和的查询 −
mysql> select CustomerId, SUM(CustomerValue) OVER (ORDER BY CustomerId) SpecificSum from DemoTable;
这将产生以下输出 −
+------------+-------------+ | CustomerId | SpecificSum | +------------+-------------+ | 1 | 10 | | 2 | 30 | | 3 | 60 | | 4 | 100 | +------------+-------------+ 4 rows in set (0.00 sec)