June 1, 2011 at 4:08 am
Hi All,
I would like to to display the last 6 month month end date for a given date. say for example,
if i give like 01/jun/2011, i have to display as below
31/dec/2010
31/jan/2011
28/feb/2011
31/mar/2011
30/apr/2011
31/may/2011
Inputs are welcome!
karthik
June 1, 2011 at 4:26 am
print getdate()
print dateadd(m,-1,getdate())
print dateadd(m,-2,getdate())
.
.
.
.
.
.
and so on.
----------
Ashish
June 1, 2011 at 4:33 am
One simple way: -
DECLARE @date DATETIME, @number INT
SET @date = '2011-06-01 00:00:00'
SET @number = 6
;WITH CTE AS (
SELECT @number-1 AS months
UNION ALL
SELECT months - 1
FROM CTE
WHERE months > 0)
SELECT DATEADD(DAY,-1,DATEADD(MONTH,-months,DATEADD(DAY,-(DAY(@date)-1),@date)))
FROM CTE
June 6, 2011 at 9:46 am
Or
SELECT
TOP 6 DATEADD(DAY,-1,DATEADD(MONTH,1-ROW_NUMBER() OVER(ORDER BY name) ,'Jun 2011'))
FROM
sys.columns
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply