Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Date of previous year previous month

Author  Topic 

kishoremcp
Starting Member

41 Posts

Posted - 2013-09-10 : 05:11:22
Hi,

I am new to sql. Need help in getting a query whichi will get previous year, previous month first day everytime i run the query.

Ex: If i run the script on 9/10/2013 then result should be 8/1/2012. (MM/DD/YYYY)

Thanks in advance.

I also need some useful books to refer and learn.

Thanks in advance.

Regards
Kishore

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-09-10 : 05:42:23
-- First day of Last Year's previous month
SELECT DATEADD(DD, -DAY(GETDATE())+1,DATEADD(MM, -13, DATEDIFF(DD,0,GETDATE())))

For example:
DECLARE @date DATETIME = '2013-08-16 15:11:53.927'
SELECT DATEADD(DD, -DAY(@date)+1,DATEADD(MM, -13, DATEDIFF(DD,0,@date)))

--
Chandu
Go to Top of Page

divya.ce
Starting Member

16 Posts

Posted - 2013-09-11 : 09:27:57
I have written two good blog post on date calculations.
http://beyondrelational.com/modules/2/blogs/51/posts/9790/date-calculations-made-easy.aspx
http://beyondrelational.com/modules/2/blogs/51/posts/9791/creating-time-dimension-with-datetime-calculated-columns.aspx

Let me know if it helps you

Divya
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-09-12 : 16:54:35
[code]
DECLARE @DateVal datetime = '20120315'--any value you may pass
SELECT DATEADD(mm,MONTH(@dateval)-2,DATEADD(yy,YEAR(@dateval)-1901,0))


output
---------------------------------
2011-02-01 00:00:00.000

[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2013-09-12 : 17:37:26
Keep it simple?
DECLARE	@dt DATETIME = '20130910'

-- SwePeso
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19010201', @dt), '19000101');



Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA
Go to Top of Page
   

- Advertisement -