使用mysql interval获取按月分组的数据

时间:2015-09-30 11:36:41

标签: mysql

我想要从我的购买表中按月分组的过去1年的记录。值得一提的是,过去两个月没有购买,包括目前的购买。 mysql查询就像下面的

SELECT Year(purchasedate) as y ,Month(purchasedate) as m, Count(*) FROM purchase WHERE productid=1001 AND purchasedate >= CURDATE() - INTERVAL 1 YEAR GROUP BY m, y

它从上次购买日期返回11个月的数据

2015 1 9177
2015 2 9914
2015 3 11672
2015 4 10521
2015 5 11873
2015 6 10449
2015 7 4057
2014 9 340
2014 10 9913
2014 11 8451
2014 12 7857

但它应该返回12个月的数据。

    2015 1 9177
    2015 2 9914
    2015 3 11672
    2015 4 10521
    2015 5 11873
    2015 6 10449
    2015 7 4057
    2015 8 0
    2015 9 0
    2014 10 9913
    2014 11 8451
    2014 12 7857

我做错了什么。提前谢谢。

1 个答案:

答案 0 :(得分:1)

试试这个

SELECT d.y, d.m, p.cnt 
FROM 
    (SELECT a.y, b.m 
    FROM (SELECT 2015 AS Y UNION ALL SELECT 2014 AS Y) a
    CROSS JOIN (SELECT 1 AS m UNION ALL SELECT 2 AS m UNION ALL SELECT 3 AS m UNION ALL SELECT 4 AS m UNION ALL SELECT 5 AS m UNION ALL SELECT 6 AS m UNION ALL SELECT 7 AS m UNION ALL SELECT 8 AS m UNION ALL SELECT 9 AS m UNION ALL SELECT 10 AS m UNION ALL SELECT 11 AS m UNION ALL SELECT 12 AS m) b
    WHERE CONCAT(a.y, '-', b.m, '-01') BETWEEN CURDATE() - INTERVAL 13 MONTH AND CURDATE() - INTERVAL 1 MONTH
    ORDER BY 1, 2) d
    LEFT OUTER JOIN
    (SELECT YEAR(purchasedate) AS Y ,MONTH(purchasedate) AS m, COUNT(*) cnt FROM purchase WHERE productid=1001 AND purchasedate >= CURDATE() - INTERVAL 1 YEAR GROUP BY m, Y) p ON d.m=p.m AND d.y=p.y
ORDER BY 1 DESC, 2

您没有做错任何事情,但MySQL无法返回数据集中不存在的月数。要解决此问题,您需要提供自己的所有月份(此查询中的表d)和LEFT JOIN来自数据集的结果