如果 MySQL 中另一列满足条件,如何对某一列中的单元格求和?
mysqlmysqli database
为此,您可以使用聚合函数 SUM() 和 GROUP BY 子句。让我们首先创建一个表 −
mysql> create table DemoTable -> ( -> EmployeeName varchar(20), -> JoiningDate date, -> Salary int -> ); Query OK, 0 rows affected (0.54 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('David','2019-11-02',400); Query OK, 1 row affected (0.52 sec) mysql> insert into DemoTable values('Robert','2018-11-25',100); Query OK, 1 row affected (0.39 sec) mysql> insert into DemoTable values('Bob','2019-12-14',600); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values('Carol','2019-11-03',300); Query OK, 1 row affected (0.23 sec)
使用 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)