MySQL:选择上个月的第一天和最后一天

时间:2016-08-25 21:12:07

标签: mysql date

使用PhpMyadmin,我有这句话:

SELECT id_order as Ref FROM t_orders WHERE DATE(invoice_date) = CURDATE()

现在我想提前重新填写上个月第一天的“当前日期”(CURDATE)。

Ankit Bajpai的答案解决了我的问题(谢谢):

SELECT id_order as Ref FROM t_orders WHERE DATE(invoice_date) >= concat(date_format(LAST_DAY(now() - interval 1 month),'%Y-%m-'),'01'); 

4 个答案:

答案 0 :(得分:1)

在MYSQL中,您可以尝试以下

上个月的第一天

select last_day(curdate() - interval 2 month) + interval 1 day

上个月的最后一天

select last_day(curdate() - interval 1 month)

当月第一天

select last_day(curdate() - interval 1 month) + interval 1 day

当月最后一天

select last_day(curdate())

答案 1 :(得分:-1)

对于MS SQL Server:

DECLARE @firstDayOfLastMonth DATETIME = DATEADD(MONTH, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
DECLARE @lastDayOfLastMonth DATETIME = DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))

SELECT @firstDayOfLastMonth;
SELECT @lastDayOfLastMonth;

答案 2 :(得分:-1)

尝试以下查询: -

SELECT id_order as Ref
FROM t_orders 
WHERE DATE(invoice_date) >= concat(date_format(LAST_DAY(now() - interval 1 month),'%Y-%m-'),'01'); 

答案 3 :(得分:-1)

仔细阅读后......你想要整个月,也就是上个月。你可以这样做:

SELECT id_order as Ref FROM t_orders 
WHERE 
DATE(invoice_date) >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
AND
DATE(invoice_date) <= DATEADD(month, DATEDIFF(MONTH, 0, GETDATE()), -1)

OR

SELECT id_order as Ref FROM t_orders 
WHERE 
MONTH(DATE(invoice_date)) = MONTH(DATEADD(MONTH,-1,GETDATE()))