views:

539

answers:

2

Here goes a yet another SQL question about dates…

I'm building a calendaring application using PHP and Postgres that would display events spanning days, weeks or possibly months. Each event has a start date and an end date, and selecting them by range is not a problem; however, it would be useful for me if Postgres could split multi-week events at the first day of each week. I've been told it can be done using GROUP BY and EXTRACT, but I'm not good enough with SQL to understand how.

The question is: can this be done, and what would the precise query look like? Currently I'm using SELECT * FROM events WHERE (range) OVERLAPS (range); and then doing the splitting in PHP, but it's clearly not optimal.

+2  A: 

You can use the Postgres function generate_series. In 8.3 and earlier, do things like

select current_date + s.a as dates from generate_series(0,14,7) as s(a);

In 8.4, you can also do

SELECT * FROM generate_series('2008-03-01 00:00'::timestamp,
                              '2008-03-04 12:00', '10 hours');
Martin v. Löwis
Thanks, I didn't know about `generate_series`. I'm currently using 8.3, so I guess I'll have to switch to 8.4 to really use the function, because applying the 8.3 example to dates seems a little difficult.
Reinis I.
It's not that hard if you combine generate_series with an interval of '1 day'; there's a good example of doing that sort of thing on a monthly basis at http://www.mail-archive.com/[email protected]/msg134699.htmlbv
Greg Smith
+1  A: 

First of all - it would be good to show some sample input and output of the query you'd like us to help you with - I, for example, don't really get what it is that you need.

Also - you might find OVERLAPS to be suboptimal, as it's not indexable. Instead you might want to use the method I described in this blog post.

depesz
Sorry for being unclear. This is an example of the results my query currently returns: <http://pastebin.com/d5021e30d>. The last two events span several months, and I'd like to split them into as many events as there are first days of the week inside that range. For example: <http://pastebin.com/d758bf244>.
Reinis I.
Sorry, the URLs are broken. These are the correct ones:* http://pastebin.com/d5021e30d* http://pastebin.com/d758bf244
Reinis I.