Search code examples
sqlpostgresqltime-seriesweekdaygenerate-series

Generate series of week intervals for given month


In a Postgres 9.1 database, I am trying to generate a series of weeks for a given month but with some constraints. I need all weeks to start on Monday and get cut when they start or end in another month.

Example:

For February, 2013 I want to generate a series like this:

         start
------------------------
2013-02-01 00:00:00+00
2013-02-04 00:00:00+00
2013-02-11 00:00:00+00
2013-02-18 00:00:00+00
2013-02-25 00:00:00+00

The query that I have now looks like this:

SELECT GREATEST(date_trunc('week', dates.d),
                date_trunc('month',dates.d)) as start
FROM generate_series(to_timestamp(1359676800),to_timestamp(1362095999), '1 week') as dates(d)

This query gets me the first 4 weeks but it's missing the week from the 25th. Is it possible to get the last week?


Solution

  • select
        greatest(date_trunc('week', dates.d), date_trunc('month',dates.d)) as start
    from generate_series('2013-02-01'::date, '2013-02-28', '1 day') as dates(d)
    group by 1
    order by 1