Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculating prior year

Status
Not open for further replies.

morechocolate

Technical User
Apr 5, 2001
225
US
I have been playing around for a while with the following

select dateadd(year,-1,(dateadd(day, -(datepart(day,somedate-1)), (dateadd(day,datediff(day,0,somedate),0)))))

which returns the last day of the previous month.

I need to return the previous year. For example if somedate is 12/31/2004, I want to return 12/31/2003. If I change the first day to year I get 12/01/2003

Thanks in advance for the help
 
Returning the last day of the previous year is easier than it looks.
Code:
declare @date datetime
set @date = '8/17/2004'
select '12/31/' + datepart(yy, dateadd(yy, -1, @date))
The last day of the year is always 12/31/XX. The only one you need to figure out is what last year was.

Denny
MCSA (2003) / MCDBA (SQL 2000)

--Anything is possible. All it takes is a little research. (Me)

[noevil]
(Not quite so old any more.)
 
for really slick techniques, see vongrunt's faq183-5842

see point #6 for "last day of ..."

r937.com | rudy.ca
 
To get last day of previous month:
Code:
select dateadd(day, -day(getdate()), getdate())

To get the previous year you can just do a datediff with year parameter:
Code:
select dateadd(year, -1, getdate())

Regards,
AA
 
Thanks everyone for your response. Yes, I agree mrdenny, it is much easier than it looks. Funny how we can sometimes make the easiest things so complicated. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top