简体   繁体   中英

How to get last year's date range?

I would like to get a date range between LastYear/1/1 until LastYear/12/31

I know I could do this

date_sub(now(), interval 1 year) . But this would get me 2013/03/08. Not sure how to change the day and the month.

SELECT *
FROM orders
WHERE dispatch_date between  `LastYear/1/1` AND `LastYear/12/31`

You can easy to create the required dates:

SELECT *
FROM orders
WHERE dispatch_date >= MAKEDATE(YEAR(NOW()) - 1, 1) -- first day of previous year
 AND dispatch_date < MAKEDATE(YEAR(NOW()), 1)  -- first day of current year

I would suggest you to use YEAR() .

SET @LastYear = YEAR(DATE_SUB(NOW(),INTERVAL 1 YEAR));
SELECT *
FROM orders
WHERE dispatch_date 
    BETWEEN CONCAT(@LastYear,'-01-01') AND CONCAT(@LastYear,'-12-31')

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