Sachin :
I am trying to get records from quarter before current quarter in MySQL. But not able to figure out how the query will be constructed.
My MySQL table:
Here's my query to get records of current quarter (Jan 2020 to March 2020):
SELECT * FROM `customers` WHERE QUARTER(`customer_date`) = QUARTER(CURRENT_DATE)
AND YEAR(`customer_date`) = YEAR(CURRENT_DATE)
ORDER BY `customer_date` DESC
But when I am using following query to get records from quarter before current quarter i.e. records from Oct 2019 to Dec 2019
, the query doesn't yield me correct result. Actually it fetches records of every quarter (Oct to Dec) of all previous years in the table:
SELECT * FROM `customers` WHERE QUARTER(`customer_date`) = QUARTER(CURRENT_DATE - INTERVAL 1 QUARTER)
ORDER BY `customer_date` DESC
I can't use YEAR
in above query. If I use the year then query will fail when it will be run in the future e.g. in the quarter of Apr 2020 to Jun 2020.
How can this query be modified to get required result?
Omari Victor Omosa :
Try this will do:
select
*
from
customers
where
quarter(`customer_date`) = quarter(current_date - interval 1 quarter)
and year(customer_date) =
(case
when quarter(curdate()) > 1 then year(current_date)
else year(current_date)-1
end)
order by
`customer_date` desc
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=297844&siteId=1