I am using PostgreSQL 14.5
I can classify the year by quarter using the Postgres keyword QUARTER
as illustrated in the documentation just like SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
. And it works. The default quarter starts with January
. Which makes complete sense. I.e, quarter one is composed of January
, February
, and March
. The others follow then. But, I wanted to make the month configurable so that the quarter can start at any month.
Eg. If the month starts in April
, April
, May
, and July
would be the first quarter.
I have started writing my custom function to come up with a solution but,
Can I do this without creating a custom function?
3
Answers
Hers is it:
You can use simple condition statement to get it done as below:
Your query:
Solution Query (quarter starts with April):
For Quarter starting with July:
fiddle
You can also use
interval
to change the actual date like @nikhil sugandh suggested.If you want April to be the starting month then you need to subtract 3 from your actual date. If the month is July then you need to subtract 6.
fiddle
The problem with the selected solution is that make the month configurable so that the quarter can start at any month is not possible; you have to change the query to change the starting month. The following are a couple custom functions which allow this configuration.
The above defines a quarter as 3 consecutive month starting with the specified month. It builds a ‘quarterly’ month calendar from that month. If an invalid month is specified the function returns
null
.The second function is a pass thru to the above. It differs in the starting month is specified as test, i.e the month name. Note is subject to local month names, but easily updated. While it is a custom function is also is a single SQL statement. That statement could then be pulled out and run standalone; you just need to pass the parameters.
Like the prior function this function returns null if an invalid month name is supplied. However, unlike the first it cannot be extracted and run standalone. (see demo containing each)