What's the most efficient way to calculate the last day of the prior quarter?
Example: given the date 11/19/2008, I want to return 9/30/2008.
Platform is SQL Server
What's the most efficient way to calculate the last day of the prior quarter?
Example: given the date 11/19/2008, I want to return 9/30/2008.
Platform is SQL Server
If @Date has the date in question
Select DateAdd(day, -1, dateadd(qq, DateDiff(qq, 0, @Date), 0))
EDIT: Thanks to @strEagle below, simpler still is:
Select dateadd(qq, DateDiff(qq, 0, @Date), -1)
Actually simpler is:
SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), -1)
Get the current date
SELECT CONVERT(DATE,GETDATE()) [Current Date]
Get the 1st date of the quarter for the current date
SELECT CONVERT(DATE, DATEADD(QQ, DATEDIFF(QQ, 0, GETDATE()) ,0)) [Current Quarter 1st Date]
Get the last date of the quarter for the current date
SELECT CONVERT(DATE,DATEADD(d, -1, DATEADD(q, DATEDIFF(q, 0, GETDATE()) +1, 0))) [Current Quarter Last Date]
Get the 1st date of the next quarter for the current date
SELECT CONVERT(DATE, DATEADD(QQ, DATEDIFF(QQ, 0, GETDATE()) +1 ,0)) [Next Quarter 1st Date]
Get the last date of the next quarter for the current date
SELECT CONVERT(DATE,DATEADD(d, -1, DATEADD(q, DATEDIFF(q, 0, GETDATE()) +2, 0))) [Next Quarter Last Date]
I came up with this (tested for all months):
select dateadd(dd,-1,dateadd(qq,datediff(qq,0,'11/19/2008'),0)), dateadd(dd,-1,dateadd(qq,datediff(qq,0,'10/19/2008'),0)), dateadd(dd,-1,dateadd(qq,datediff(qq,0,'12/19/2008'),0))
It might turn out to be the simplest.
convert(varchar, dateadd(dd,-1,dateadd(qq,1,DATEADD(qq, DATEDIFF(qq,0,YOUR_DATE), 0))),112)
you also can change 112 base on this below list
In amazon redshift:
Last day of the previous quarter:
select dateadd(day,-1,DATE_TRUNC('qtr', current_date)) from whatever
Last day of current quarter:
select dateadd(qtr,1,dateadd(day,-1,DATE_TRUNC('qtr', current_date))) from whatever