如何使用MySQL按月对表中的值求和?
为此,请使用EXTRACT()
,这将允许您提取特定的月份记录。例如,将一月份(与年份无关)的所有价格相加。
让我们首先创建一个-
mysql> create table DemoTable1415 -> ( -> ProductPurchaseDate date, -> ProductPrice int -> );
使用insert在表中插入一些记录-
mysql> insert into DemoTable1415 values('2019-01-12',560); mysql> insert into DemoTable1415 values('2018-01-14',1060); mysql> insert into DemoTable1415 values('2017-03-21',780); mysql> insert into DemoTable1415 values('2016-09-01',800); mysql> insert into DemoTable1415 values('2019-01-14',100);
使用选择显示表中的所有记录-
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)