如何在 MySQL 中对列元素求和?


使用聚合函数 sum() 对 MySQL 中的列元素求和。语法如下 −

select sum(yourColumnName1) as anyVariableName1,sum(yourColumnName2) as anyVariableName2,sum(yourColumnName3) as anyVariableName3,............N from yourTableName;

为了理解以上语法,让我们创建一个表。以下是创建表的查询 −

mysql> create table SumDemoOnColumns
   −> (
   −> First int,  
   −> Second int,
   −> Third int
   −> );
Query OK, 0 rows affected (0.56 sec)

使用 insert 命令在表中插入一些数据。查询如下 −

mysql> insert into SumDemoOnColumns values(10,20,30);
Query OK, 1 row affected (0.18 sec)

mysql> insert into SumDemoOnColumns values(40,50,60);
Query OK, 1 row affected (0.32 sec)

mysql> insert into SumDemoOnColumns values(70,80,90);
Query OK, 1 row affected (0.10 sec)

mysql> insert into SumDemoOnColumns values(100,110,120);
Query OK, 1 row affected (0.16 sec)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from SumDemoOnColumns;

以下是输出 −

+-------+--------+-------+
| First | Second | Third |
+-------+--------+-------+
|    10 |     20 |    30 |
|    40 |     50 |    60 |
|    70 |     80 |    90 |
|   100 |    110 |   120 |
+-------+--------+-------+
4 rows in set (0.00 sec)

以下是获取列总和的查询 −

mysql> select sum(First) as First,sum(Second) as Second,sum(Third) as Third from SumDemoOnColumns;

以下是输出 −

+-------+--------+-------+
| First | Second | Third |
+-------+--------+-------+
|   220 |    260 |   300 |
+-------+--------+-------+
1 row in set (0.00 sec)

更新于: 2019 年 7 月 30 日

442 次浏览

开始您的 职业

完成课程获取认证

开始
广告