Being a business analyst, I spend a lot of time writing SQL scripts. I’m writing this post to have a point of reference to some handy sql date scripts that I use and will probably use often when scripting in future requests. I’ll continue adding to this post as come across some other handy SQL date scripts.
Dates of Quarters
- First date of Previous QRT = SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) – 1, 0)
- Last date of Previous QRT = SELECT DATEADD(dd, -1, DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0))
- First date of Current QRT = SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)
- Last date of Current QRT = SELECT DATEADD (dd, -1, DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) +1, 0))
- First date of Next QRT = SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) +1, 0)
- Last date of Next QRT = SELECT DATEADD (dd, -1, DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) +2, 0))
- Week of the QRT = SELECT DATEPART(WEEK, GETDATE()) – DATEPART(WEEK, DATEADD(qq, DATEDIFF(qq,0,GETDATE()), 0))+ 1
Dates of Year
- First date of Previous Year = SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) – 1, 0)
- Last date of Previous Year = SELECT DATEADD(dd, -1, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0))
- First date of Current Year = SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
- Last date of Current Year = SELECT DATEADD (dd, -1, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) +1, 0))
- First date of Next Year = SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0)
- Last date of Next Year = SELECT DATEADD (dd, -1, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) +2, 0))
Leave a Reply