一个带有字符串字段的表,其中存储了日期(不建议我更改字段类型。这会导致危险)。
+--+----------+------+
|id|date |amount|
+--+----------+------+
|1 |23-03-2014|5000 |
+--+----------+------+
|2 |25-03-2014|3000 |
+--+----------+------+
|3 |21-04-2014|3000 |
+--+----------+------+
|4 |25-04-2014|4000 |
+--+----------+------+
我想编写一个模型函数,它将返回表中按月分组的金额总和。我该怎么办?它将显示输出
03 - 8000
04 - 7000
答案 0 :(得分:1)
SELECT MONTH(date_field) as mon, SUM(amount) as total FROM table_name GROUP BY MONTH(date_field);
更新
SELECT SUBSTR(date_field,6,2) as mon, SUM(amount) as total FROM table_name GROUP BY mon;
答案 1 :(得分:0)
您可以尝试以下查询
SELECT SUM(amount) FROM table GROUP BY MONTH(date)
答案 2 :(得分:0)
尝试MONTH()
SELECT MONTH(date),SUM(amount) FROM table GROUP BY MONTH(date)