如何用 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)

更新於: 2019 年 11 月 12 日

2K+ 次瀏覽

啟動您的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.