HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

Generate a series of months within a period

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
periodwithingeneratemonthsseries

Problem

I want to generate a series of months within a specific time period.

I have tried:

select  GENERATE_SERIES( '06/25/2016'::DATE, '12/15/2016'::DATE, '1 month' )


It returns:

"generate_series"
"2016-06-25 00:00:00-06"
"2016-07-25 00:00:00-06"
"2016-08-25 00:00:00-06"
"2016-09-25 00:00:00-06"
"2016-10-25 00:00:00-06"
"2016-11-25 00:00:00-07"


There is an issue at the end date. I want the result as follows:

"generate_series"
"2016-06-25 00:00:00-06"
"2016-07-25 00:00:00-06"
"2016-08-25 00:00:00-06"
"2016-09-25 00:00:00-06"
"2016-10-25 00:00:00-06"
"2016-11-25 00:00:00-07"
"2016-12-15 00:00:00-07"


I am using PostgreSQL.

Solution

Evan explains why the generate_series() cannot do by itself what you want. But it can be done with a simple UNION:

select generate_series('2016-06-25'::timestamp, '2016-12-15', '1 month') 
         as g_date 
union 
select '2016-12-15'
-- order by g_date 
;


or UNION ALL:

select generate_series('2016-06-25'::timestamp, 
                       '2016-12-15' - interval '1 day', 
                       '1 month') as g_date 
union all
select '2016-12-15' ;


Also note that generate_series() output is of timestamp without
timezone
type. if you want a date type, you need to cast:

select generate_series('2016-06-25'::timestamp, 
                       '2016-12-15' - interval '1 day', 
                       '1 month')::date as g_date 
union all
select '2016-12-15'::date ;

Code Snippets

select generate_series('2016-06-25'::timestamp, '2016-12-15', '1 month') 
         as g_date 
union 
select '2016-12-15'
-- order by g_date 
;
select generate_series('2016-06-25'::timestamp, 
                       '2016-12-15' - interval '1 day', 
                       '1 month') as g_date 
union all
select '2016-12-15' ;
select generate_series('2016-06-25'::timestamp, 
                       '2016-12-15' - interval '1 day', 
                       '1 month')::date as g_date 
union all
select '2016-12-15'::date ;

Context

StackExchange Database Administrators Q#159406, answer score: 5

Revisions (0)

No revisions yet.