如何用 MySQL 按照月份计算表中值的总和?
要执行此操作,请使用 EXTRACT(),它允许你提取特定月份的记录。例如,添加 1 月份的所有价格(与年份无关)。
我们首先创建一个 -
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)
广告