Calculate the last day of the quarter

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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

回答1:

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)  


回答2:

Actually simpler is:

SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), -1) 


回答3:

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] 


回答4:

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.



回答5:

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



回答6:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!