简体   繁体   中英

MySQL: Select with first and last day of previous month

Using PhpMyadmin, I have this sentence working:

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

Now I want to reemplace "current date" (CURDATE) for the first day of previous month in advance.


The answer of Ankit Bajpai solved my problem (thank you):

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

in MYSQL you can try the below

First day of Previous Month

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

Last day of Previous Month

select last_day(curdate() - interval 1 month)

First day of Current Month

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

Last day of Current Month

select last_day(curdate())

For 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;

Try following query:-

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

After reading closely... you want the entire month, of the previous month. You can do this:

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()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM