简体   繁体   中英

how to find the last quarter in MySQL

This should be a simple question but I still cannot get some valid result. I'm using the Workbench. I'm trying to get the last quarter from the current date.

When I query the current quarter, I get the right answer:

SELECT quarter(curdate());
1

But when I want the last quarter:

SELECT (quarter(curdate())-1);

I still get 1.

I also tried (found it online):

SELECT LAST_QTR(curdate());

but I get:

Error code: 1305. FUNCTION LAST_QTR does not exist

Can someone help figure this out? Thank you in advance.

试试这个,看看是否适合您。

SELECT quarter(curdate() - INTERVAL 1 QUARTER);

Try this:

SELECT IF((QUARTER(curdate())-1) = 0, 4, QUARTER(curdate()) - 1) as last_quarter

Return the current quarter - 1 if the quarter is greater than 1. Otherwise if the current quarter is 1 return 4.

Get Last Quarter End Date

SELECT CASE WHEN QUARTER(curdate()) = 1 
            THEN MAKEDATE(YEAR(CURDATE() - INTERVAL 1 YEAR), 1)  + INTERVAL 4 QUARTER - INTERVAL    1 DAY 
            ELSE MAKEDATE(YEAR(CURDATE()),1)+ INTERVAL QUARTER(CURDATE()) - 1 QUARTER - INTERVAL    1 DAY  END

Replace the Curdate() with the date you needed

Here is the way to get all the previous/last quarter records in MySql or WordPress.

Note : visited is the datetime column into the table

"SELECT * FROM tbl_users WHERE QUARTER(visited) = QUARTER(curdate() - INTERVAL 1 quarter)"

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