WHERE
order_customFields.order_customFields_order_date >= '2016-12-01' AND
order_customFields.order_customFields_order_date <= '2016-12-31'
如何选择上个月的数据,而非当前日期 - 30天?例如,在1月的任何一天,它总是从1dec到31dec。
答案 0 :(得分:1)
这是一种方法:
WHERE order_customFields.order_customFields_order_date >= date_sub(date_sub(curdate(), interval day(curdate()) - 1 day), interval 1 month) and
order_customFields.order_customFields_order_date < date_sub(curdate(), interval day(curdate()) - 1 day)
请注意,表达式:date_sub(curdate(), interval day(curdate()) - 1 day)
将返回当月的第一天。
答案 1 :(得分:1)
E.g:
SELECT * FROM my_table;
+------------+
| dt |
+------------+
| 2016-11-01 |
| 2016-11-04 |
| 2016-11-06 |
| 2016-11-07 |
| 2016-11-09 |
| 2016-11-10 |
| 2016-11-12 |
| 2016-11-13 |
| 2016-11-14 |
| 2016-11-15 |
| 2016-11-16 |
| 2016-11-17 |
| 2016-11-18 |
| 2016-11-19 |
| 2016-11-20 |
| 2016-11-21 |
| 2016-11-22 |
| 2016-11-23 |
| 2016-11-24 |
| 2016-11-25 |
| 2016-11-26 |
| 2016-11-28 |
| 2016-12-01 |
| 2016-12-03 |
| 2016-12-04 |
| 2016-12-07 |
| 2016-12-11 |
| 2016-12-13 |
| 2016-12-15 |
| 2016-12-18 |
| 2016-12-19 |
| 2016-12-22 |
| 2016-12-25 |
| 2016-12-28 |
| 2017-01-01 |
| 2017-01-04 |
| 2017-01-07 |
| 2017-01-11 |
| 2017-01-14 |
| 2017-01-15 |
| 2017-01-16 |
| 2017-01-19 |
+------------+
SELECT *
FROM my_table
WHERE dt BETWEEN DATE_FORMAT(CURDATE()-INTERVAL 1 MONTH,'%Y-%m-01')
AND LAST_DAY(CURDATE()-INTERVAL 1 MONTH);
+------------+
| dt |
+------------+
| 2016-12-01 |
| 2016-12-03 |
| 2016-12-04 |
| 2016-12-07 |
| 2016-12-11 |
| 2016-12-13 |
| 2016-12-15 |
| 2016-12-18 |
| 2016-12-19 |
| 2016-12-22 |
| 2016-12-25 |
| 2016-12-28 |
+------------+