比较月初至日期与上个月同期MySQL

时间:2018-03-08 15:49:51

标签: mysql

我试图比较从月初到日期的总购买量与上个月和前一个月的同一时期。

3月1日至7月,相比2月1日至7日和1月1日至7日

到目前为止,我已经能够获得月到日,但我不得不手动输入上个月的日期进行比较,我会使用什么查询来自动获取这些以前的日期?

当前代码

SELECT *,
current_downloads/M_1 AS `M_1_Ratio`,
current_downloads/M_2 AS `M_2_Ratio`
FROM 
(SELECT count(*) AS current_downloads
FROM `purchase`
WHERE date(`purchase`.`timestamp`) >= DATE_FORMAT(NOW() ,'%Y-%m-01')) t1
JOIN 
(SELECT count(*) AS M_1
FROM `purchase`
WHERE date(`purchase`.`timestamp`) BETWEEN {{date3}} AND {{date4}}) t2
JOIN 
(SELECT count(*) AS M_2
FROM `purchase`
WHERE date(`purchase`.`timestamp`) BETWEEN {{date5}} AND {{date6}}) t3

1 个答案:

答案 0 :(得分:1)

您可以使用DATE_SUB()获取这些计算并更改要减去的INTERVAL,一个月或两个月

e.g。

SELECT DATE(NOW());
+-------------+
| DATE(NOW()) |
+-------------+
| 2018-03-08  |
+-------------+

SELECT DATE_SUB(DATE_FORMAT(NOW(),'%Y-%m-01'), INTERVAL 1 MONTH);
+-----------------------------------------------------------+
| DATE_SUB(DATE_FORMAT(NOW(),'%Y-%m-01'), INTERVAL 1 MONTH) |
+-----------------------------------------------------------+
| 2018-02-01                                                |
+-----------------------------------------------------------+

SELECT DATE_SUB(DATE(NOW()), INTERVAL 1 MONTH);
+-----------------------------------------+
| DATE_SUB(DATE(NOW()), INTERVAL 1 MONTH) |
+-----------------------------------------+
| 2018-02-08                              |
+-----------------------------------------+