Re: Month/year between two dates

From: Steve Crawford <scrawford(at)pinpointresearch(dot)com>
To: Bor <dborovnik(at)gmail(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Month/year between two dates
Date: 2009-08-11 22:32:38
Message-ID: 4A81F186.6020701@pinpointresearch.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Bor wrote:
> Hi to all,
>
> I have a very simple question. Let's say that I have three records (id, date
> from, date to):
>
> 1 2009-01-01 2009-08-31
> 2 2009-08-01 2009-08-10
> 3 2009-08-11 2009-08-31
>
> Now I want to get records, "related" to a single month/year data (two
> integers). For 2009/08 (int1 = 2009, int2 = 8) I should get all three
> records, for 2009/05 only record 1, but for 2009/11 none of the records.
>
> Is there any simple way to do this? A query would do :).
>
> Thanks alot.
>
Lots of ways. The following springs to mind but I'm sure there are
simpler ways (I'm assuming the date_from and date_to are data-type date
and you are stuck with using int for year and month).

Use date_trunc to convert any date in a month to the first of the month
and the following should work (untested):
...
date_trunc('month', date_from) <= (int1::text || '-' || int2::text ||
'-1')::date and
date_trunc('month', date_to) >= (int1::text || '-' || int2::text ||
'-1')::date
...

Cheers,
Steve

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Denis BUCHER 2009-08-11 22:35:48 Re: mail alert
Previous Message Peter Headland 2009-08-11 20:13:05 Re: Race hazard deleting using CTID?