为此,可以将聚合函数SUM()
与GROUP BY子句一起使用。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> EmployeeName varchar(20), -> JoiningDate date, -> Salary int -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('David','2019-11-02',400); mysql> insert into DemoTable values('Robert','2018-11-25',100); mysql> insert into DemoTable values('Bob','2019-12-14',600); mysql> insert into DemoTable values('Carol','2019-11-03',300);
使用select语句显示表中的所有记录-
mysql> select * from DemoTable;
这将产生以下输出-
+--------------+-------------+--------+ | EmployeeName | JoiningDate | Salary | +--------------+-------------+--------+ | David | 2019-11-02 | 400 | | Robert | 2018-11-25 | 100 | | Bob | 2019-12-14 | 600 | | Carol | 2019-11-03 | 300 | +--------------+-------------+--------+ 4 rows in set (0.00 sec)
如果满足另一列中的条件,这是对一列中的单元格求和的查询-
mysql> select year(JoiningDate) as JoiningYear, -> month(JoiningDate) as JoiningMonth, -> sum(Salary) as Total, -> group_concat(EmployeeName) as Name -> from DemoTable -> group by JoiningYear,JoiningMonth;
这将产生以下输出-
+-------------+--------------+-------+-------------+ | JoiningYear | JoiningMonth | Total | Name | +-------------+--------------+-------+-------------+ | 2018 | 11 | 100 | Robert | | 2019 | 11 | 700 | David,Carol | | 2019 | 12 | 600 | Bob | +-------------+--------------+-------+-------------+ 3 rows in set (0.04 sec)