如何使用 MySQL 按月对表中的值进行求和?
mysqlmysqli database
为此,请使用 EXTRACT(),它允许您提取特定月份的记录。例如,添加一月份的所有价格(无论年份如何)。
让我们首先创建一个 −
mysql> create table DemoTable1415 -> ( -> ProductPurchaseDate date, -> ProductPrice int -> ); Query OK, 0 rows affected (0.53 sec)
使用 insert 在表中插入一些记录 −
mysql> insert into DemoTable1415 values('2019-01-12',560); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1415 values('2018-01-14',1060); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1415 values('2017-03-21',780); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1415 values('2016-09-01',800); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1415 values('2019-01-14',100); Query OK, 1 row affected (0.16 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1415;
这将产生以下输出 −
+---------------------+--------------+ | ProductPurchaseDate | ProductPrice | +---------------------+--------------+ | 2019-01-12 | 560 | | 2018-01-14 | 1060 | | 2017-03-21 | 780 | | 2016-09-01 | 800 | | 2019-01-14 | 100 | +---------------------+--------------+ 5 rows in set (0.00 sec)
以下是按月份对表中的值进行求和的查询 −
mysql> select extract(MONTH from ProductPurchaseDate) as month,sum(ProductPrice) as total_value from DemoTable1415 -> group by month;
这将产生以下输出 −
+-------+-------------+ | month | total_value | +-------+-------------+ | 1 | 1720 | | 3 | 780 | | 9 | 800 | +-------+-------------+ 3 rows in set (0.00 sec)