获取每一列求和的 MySQL 查询,且每一列的值数相同?


您可以为此使用聚合函数 SUM()。我们首先创建一个表 -

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstValue int,
   SecondValue int,
   ThirdValue int
   );
Query OK, 0 rows affected (0.57 sec)

使用 insert 命令在表中插入一些记录 -

mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(10,20,30);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(60,50,40);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(80,90,100);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(20,10,0);
Query OK, 1 row affected (0.23 sec)

以下是使用 select 语句显示表中所有记录的查询 -

mysql> select *from DemoTable;

将生成以下输出 -

+----+------------+-------------+------------+
| Id | FirstValue | SecondValue | ThirdValue |
+----+------------+-------------+------------+
| 1  | 10         | 20          | 30         |
| 2  | 60         | 50          | 40         |
| 3  | 80         | 90          | 100        |
| 4  | 20         | 10          | 0          |
+----+------------+-------------+------------+
4 rows in set (0.00 sec)

以下是获取每一列求和的查询,且每一列的值数相同 -

mysql> select sum(FirstValue),sum(SecondValue),sum(ThirdValue) from DemoTable;

将生成以下输出 -

+-----------------+------------------+-----------------+
| sum(FirstValue) | sum(SecondValue) | sum(ThirdValue) |
+-----------------+------------------+-----------------+
| 170             | 170              | 170             |
+-----------------+------------------+-----------------+
1 row in set (0.00 sec)

更新时间:30-Jul-2019

353 次浏览

开启您的职业生涯

通过完成课程获得认证

开始
广告