如何在 MySQL 中根据特定月份的记录对选定的列值求和?
mysqlmysqli database
首先我们创建一个表 −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, PurchaseDate date, SalePrice int ); Query OK, 0 rows affected (0.51 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(PurchaseDate,SalePrice) values('2018-01-10',450); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(PurchaseDate,SalePrice) values('2019-12-25',1000); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(PurchaseDate,SalePrice) values('2016-12-02',5560); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(PurchaseDate,SalePrice) values('2015-02-20',4550); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(PurchaseDate,SalePrice) values('2015-12-11',4110); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+----+--------------+-----------+ | Id | PurchaseDate | SalePrice | +----+--------------+-----------+ | 1 | 2018-01-10 | 450 | | 2 | 2019-12-25 | 1000 | | 3 | 2016-12-02 | 5560 | | 4 | 2015-02-20 | 4550 | | 5 | 2015-12-11 | 4110 | +----+--------------+-----------+ 5 rows in set (0.00 sec)
以下是根据特定月份对 MySQL 中选定列值求和的查询。例如,这里只为第 12 个月即 12 月的 PurchaseDate 添加了 SalePrice −
mysql> select SUM(SalePrice) from DemoTable where month(PurchaseDate)=12;
以上仅为选定月份即第 12 个月 12 月添加了记录 (SalePrice) −
2019-12-25 2016-12-02 2015-12-11
这将产生以下输出 −
+----------------+ | SUM(SalePrice) | | 10670 | +----------------+ 1 row in set (0.00 sec)