简体   繁体   中英

Group by month/year and sum all data

I'm trying to group some registers by months, having their values added, but no success up to now. I've been looking through the questions but haven't found this one.

My table is something like:

+----+------------+--------+--------+
| Id |    Date    | Field1 | Field2 |
+----+------------+--------+--------+
|  1 | 2014-02-01 |      4 |      5 |
|  2 | 2014-02-01 |      2 |      9 |
|  3 | 2014-02-20 |      2 |      6 |
|  4 | 2014-03-01 |      1 |      4 |
|  5 | 2014-04-03 |      1 |      5 |
+----+------------+--------+--------+

And I would like to finish with this:

+---------+--------+--------+
|  Date   | Field1 | Field2 |
+---------+--------+--------+
| 2014-02 |      8 |     20 |
| 2014-03 |      1 |      4 |
| 2014-04 |      1 |      5 |
+---------+--------+--------+

Any advice?

One way would be to group on the result of MySQL's DATE_FORMAT() function:

SELECT   DATE_FORMAT(Date, '%Y-%m') Date, SUM(Field1) Field1, SUM(Field2) Field2
FROM     my_table
GROUP BY DATE_FORMAT(Date, '%Y-%m')

See it on sqlfiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM