SQL

SQL: Select Months Between Date Range

Recently I have to do a report with data grouped by month. The query below will give you all the months between a given date range.

;with ayear(tDate) as
(
    select 
		CAST(CAST(YEAR(@StartDate) AS varchar) + '-' + CAST(MONTH(@StartDate) AS varchar) + '-1' AS DATETIME) tDate
    
    union all
    
    select 
		DATEADD(MONTH, 1, tDate) as tDate
    from ayear
    where tDate < DATEADD(MONTH, -1, @EndDate)
)

select * from ayear

Cheers – Sy

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s