SQL按名称,月,年分组的数字总和

时间:2018-07-09 16:18:27

标签: mysql sql group-by

我有下表

Name | Number | Date
ACB  |      2 | 01.01.1970
ACB  |      3 | 02.01.1970
ABC  |      1 | 01.02.1970
DEF  |     10 | 01.01.1970
DEF  |     20 | 01.02.1970

我正在寻找一个给我这样结​​果的SQL查询

Name | Sum | Month | Year
ABC  |   5 |    01 | 1970
ABC  |   1 |    02 | 1970
DEF  |  10 |    01 | 1970
DEF  |  20 |    02 | 1970

我能做的是获得一个名字的所有条目的总和

SELECT Name, SUM(Number) AS Sum FROM table GROUP BY Name

尝试如下所示的操作时,出现错误“表中未找到'mon'”

SELECT Name, SUM(Number) AS Sum, MONTH(Date) AS mon FROM table GROUP BY Name, mon

在GROUP语句中包含MONTH()函数也无济于事,在这种情况下,数据库将引发“意外的'('”错误。

感谢帮助!

2 个答案:

答案 0 :(得分:3)

GROUP BY子句指定结果集中的唯一行。您需要月份和年份,所以应该在GROUP BY中:

SELECT Name, SUM(Number) AS Sum, MONTH(Date) AS mon, YEAR(Date) as year
FROM table
GROUP BY Name, MONTH(Date), YEAR(Date) ;

答案 1 :(得分:0)

您也可以改用subquery

select distinct Name, MONTH(Date) AS mon, YEAR(Date) as year,
       (select sum(t1.Number) 
        from table t1 
        where t1.Name = t.Name and
              MONTH(t1.Date) = MONTH(t.Date) and 
              YEAR(t1.Date) =  YEAR(t.Date)
       ) as Sum
from table t;