先创建一个表:

CREATE TABLE DemoTable (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstValue int,
   SecondValue int,
   ThirdValue int
);

插入一些数据:

insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(10,20,30);
insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(60,50,40);
insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(80,90,100);
insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(20,10,0);

查询一下:

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)

每一列之和:

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)

每一行之和:

SELECT SUM(FirstValue)+SUM(SecondValue)+SUM(ThirdValue) AS total FROM demotable WHERE id = 1;

输出:

+-------+
| total |
+-------+
|    60 |
+-------+
1 row in set (0.00 sec)

本文来源:
MySQL query to get sum of each column where every column has same number of values?

ChatGPT-4 指导完成?

标签: none

评论已关闭