MySQL查询获取每列的总和,其中每列具有相同数量的值?
您可以SUM()
为此使用聚合函数。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstValue int, SecondValue int, ThirdValue int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(10,20,30); mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(60,50,40); mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(80,90,100); mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(20,10,0);
以下是使用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)