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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Date Calculation

Author  Topic 

SBLatta
Starting Member

33 Posts

Posted - 2010-11-16 : 13:27:38
For some reason, I can't seem to wrap my head around this one:

What formula would let me calculate the most recent previous September 30 from today (ie. getdate())?

Bustaz Kool
Master Smack Fu Yak Hacker

1834 Posts

Posted - 2010-11-16 : 19:28:53
If you had a Calendar table....

select max(MyDate)
from Calendar
where MyDate < GetDate()
and Month(MyDate) = 9
and Day(MyDate) = 30

You can decide how you want to handle the time portion of GetDate() when it falls on a September, 30.

=======================================
Man is least himself when he talks in his own person. Give him a mask, and he will tell you the truth. -Oscar Wilde, writer (1854-1900)
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-11-17 : 05:11:28
select dateadd(month,9,DATEADD(year,datediff(year,0,getdate()),0))-1

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

SBLatta
Starting Member

33 Posts

Posted - 2010-11-17 : 10:17:50
quote:
Originally posted by madhivanan

select dateadd(month,9,DATEADD(year,datediff(year,0,getdate()),0))-1

Madhivanan

Failing to plan is Planning to fail



Thanks Madhivanan, that formula worked!

Let me see if I actual understand what you did:

DATEDIFF(year,0,getdate()) is calculating the number of years between today and the default start date 1/1/1900 = 110 years

DATEADD(year,110,0) is taking the 110 years from the above portion of the formula and adding it to 1/1/1900 = 1/1/2010

DATEADD(month,9,1/1/2010) is adding 9 months to the above result, so 10/1/2010

Finally, 1 is being subtracted from the result to give 9/30/10

Is that correct? So, in SQL, adding or subtracting an integer to a date will add or subtract that number of days?

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-11-17 : 10:20:15
Yes. You are correct

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -