如何在 MySQL 中基于特定月份记录求和选定列值?
我们首先创建一个表 −
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 中求和所选列值所需的查询。例如,这里只增加了 PurchaseDate 为 12 月(即 12 月)的 SalePrice −
mysql> select SUM(SalePrice) from DemoTable where month(PurchaseDate)=12;
上面的代码仅添加了特定月份的记录(SalePrice),即 12 月 −
2019-12-25 2016-12-02 2015-12-11
这将生成以下输出 −
+----------------+ | SUM(SalePrice) | | 10670 | +----------------+ 1 row in set (0.00 sec)
广告