如何在每个月分组时获取最近3个月的记录

时间:2017-12-24 09:43:34

标签: mysql sql

请问如何在过去3个月内对我的MySQL表中的记录进行汇总,但是按月分组。

我想要这样的事情:

select SUM(amount) from table where.....
group by month

我正在执行以下操作,但它没有返回任何结果

SELECT MONTHNAME(a.created_at) MONTH, YEAR(a.created_at) YEAR, SUM(a.credit) as credit, SUM(a.debit)
        FROM telco_transactions AS a
        WHERE a.telco_id = '1' and DATE(a.created_at) = DATE_ADD(NOW(), INTERVAL -3 MONTH)
        GROUP BY MONTHNAME(a.created_at), YEAR(a.created_at);

3 个答案:

答案 0 :(得分:0)

我会试试这个:

SELECT SUM(records) 
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE()) 
GROUP BY DATEPART(MONTH, Date_Column)

答案 1 :(得分:0)

select T.date_time, SUM(T.amount) from (
    -> select * from TEST_TABLE where date_time >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH) and date_time <= CURDATE())
    -> as T GROUP BY MONTH(T.date_time);

test_table 类似于

+------------+--------+
| date_time  | amount |
+------------+--------+
| 2017-12-24 |     30 |
| 2017-09-24 |     30 |
| 2017-12-04 |     30 |
| 2017-11-24 |     30 |
| 2017-11-09 |     30 |
| 2017-10-24 |     30 |
+------------+--------+

并且查询的 输出 类似于

+------------+---------------+
| date_time  | SUM(T.amount) |
+------------+---------------+
| 2017-09-24 |            30 |
| 2017-10-24 |            30 |
| 2017-11-24 |            60 |
| 2017-12-24 |            60 |
+------------+---------------+

答案 2 :(得分:0)

我找到了答案

SELECT MONTHNAME(a.created_at) as tmonth, YEAR(a.created_at) as tYear,
        SUM(a.credit) as credit, SUM(a.debit)
        FROM telco_transactions AS a
        WHERE a.telco_id = '1' and DATE(a.created_at) BETWEEN DATE(NOW())-INTERVAL 3 MONTH AND DATE(NOW())
        GROUP BY MONTHNAME(a.created_at), YEAR(a.created_at);