SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Date of previous year previous month
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

kishoremcp
Starting Member

India
39 Posts

Posted - 09/10/2013 :  05:11:22  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

India
2224 Posts

Posted - 09/10/2013 :  05:42:23  Show Profile  Reply with Quote
-- 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

India
16 Posts

Posted - 09/11/2013 :  09:27:57  Show Profile  Reply with Quote
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

India
52325 Posts

Posted - 09/12/2013 :  16:54:35  Show Profile  Reply with Quote

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



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

SwePeso
Patron Saint of Lost Yaks

Sweden
30282 Posts

Posted - 09/12/2013 :  17:37:26  Show Profile  Visit SwePeso's Homepage  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.08 seconds. Powered By: Snitz Forums 2000