Teradata - Month End Date

Sql Server:
Calculating the last day of the month in SQL Server is pretty simple.
Run the following piece of code and its done.
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
CurrentMonthEnd_Day
ResultSet:
CurrentMonthEnd_Day
———————–
2010-08-31 23:59:59.000


Teradata:
However, with reference to Teradata SQL, in our day to day queries in a datawarehouse environment very frequently we need to play with the month end dates that are mostly kept in the date dimension table with one field, i.e. the month end date field.
You might require to fetch the month end date which is 4 years back. usually the simplest way in this case will be to calculate 48 months back from the current month end date (in case the monthe end date that long is not stored into the database). This is fair. The piece of code required to do is simple.
SELECT (ADD_MONTHS(CAST('2012/08/31' AS DATE),-48))
Result:
2008/08/31
Now trying this simple thing will not work if its a leap year anywhere:
i.e. SELECT (ADD_MONTHS(CAST('2012/02/28' AS DATE),-48))
Result:
2008/02/28 -- Wrong.
Solution?? simple.
SELECT (ADD_MONTHS(CAST('2012/02/28' AS DATE) + 1,-48)-1)
Result:
2008/02/29 -- Correct.
This would definitely work with others. e.g.
SELECT (ADD_MONTHS(CAST('2012/08/31' AS DATE)+1,-48)-1)
Result:
2008/08/31

Comments

Popular posts from this blog

Automatic Replenishment ~ Warehouse Management (WM) in SAP

Cross Domain Webix Post