添加同月内发生的值:mysql

时间:2016-12-12 22:16:00

标签: mysql date datetime

我有一张这样的表:

Date                     Name     Qty
2016-09-13 00:00:00      John     2
2016-09-15 00:00:00      Matt     3
2016-09-21 00:00:00      Rich     1
2016-09-23 00:00:00      Matt     1
2016-10-05 00:00:00      John     1
2016-10-07 00:00:00      Matt     3
2016-10-12 00:00:00      Rich     0
2016-10-23 00:00:00      Matt     2

如何使用MySQL检索对应于同月的所有Qty值的添加并将该信息放在视图上?

2 个答案:

答案 0 :(得分:2)

SELECT sum(Qty) as sum, month(date) as month, year(date) as year FROM table_name GROUP BY month(date), year(date) 

将返回

 sum    month   year    
 4      12      2015
 10     12      2016

答案 1 :(得分:1)

您可能想要的可能是以下查询之一:

SELECT YEAR(`Date`) AS yr, MONTH(`Date`) AS mnt, SUM(Qty) AS Qty
FROM `table1`
GROUP BY YEAR(`Date`), MONTH(`Date`)

SELECT EXTRACT(YEAR_MONTH FROM `Date`) AS mnt, SUM(Qty) as Qty
FROM `table1`
GROUP BY EXTRACT(YEAR_MONTH FROM `Date`)

此查询应该产生如下内容:

 mnt     | qty
---------+-----
 2016-09 | 7
 2016-10 | 6

MySQL函数EXTRACT()只能返回一些components of a date