Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id D0297634C5F for ; Tue, 11 Aug 2009 19:32:44 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 80992-04 for ; Tue, 11 Aug 2009 22:32:41 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from polaris.pinpointresearch.com (66-7-238-130.static-ip.telepacific.net [66.7.238.130]) by mail.postgresql.org (Postfix) with ESMTP id 06E2D634C2B for ; Tue, 11 Aug 2009 19:32:42 -0300 (ADT) Received: from [192.168.1.179] (betelgeuse.pinpointresearch.com [192.168.1.179]) by polaris.pinpointresearch.com (Postfix) with ESMTP id 30348E00EC84; Tue, 11 Aug 2009 15:32:39 -0700 (PDT) Message-ID: <4A81F186.6020701@pinpointresearch.com> Date: Tue, 11 Aug 2009 15:32:38 -0700 From: Steve Crawford User-Agent: Thunderbird 2.0.0.21 (X11/20090318) MIME-Version: 1.0 To: Bor CC: pgsql-sql@postgresql.org Subject: Re: Month/year between two dates References: <24917400.post@talk.nabble.com> In-Reply-To: <24917400.post@talk.nabble.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-2.599 tagged_above=-10 required=5 tests=BAYES_00=-2.599 X-Spam-Level: X-Archive-Number: 200908/51 X-Sequence-Number: 32960 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