Received: from localhost (maia-4.hub.org [200.46.204.183]) by postgresql.org (Postfix) with ESMTP id 428359FBC6A for ; Thu, 5 Apr 2007 13:04:29 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 20124-09 for ; Thu, 5 Apr 2007 13:04:16 -0300 (ADT) X-Greylist: delayed 00:45:05.22393 by SQLgrey-1.7.4 Received: from mail.ringways.co.uk (unknown [80.193.83.131]) by postgresql.org (Postfix) with ESMTP id 7F7E39FBC7E for ; Thu, 5 Apr 2007 13:04:16 -0300 (ADT) Received: from eddie.ringways.co.uk ([10.1.1.115]) by mail.ringways.co.uk with esmtp (Exim 4.62) (envelope-from ) id 1HZULB-0001pm-LY for pgsql-sql@postgresql.org; Thu, 05 Apr 2007 16:57:37 +0100 From: Gary Stainburn Organization: Ringways Garages Ltd To: pgsql-sql@postgresql.org Subject: SOLVED - Another date range join problem Date: Thu, 5 Apr 2007 17:03:04 +0100 User-Agent: KMail/1.9.5 References: <200704051617.59022.gary.stainburn@ringways.co.uk> In-Reply-To: <200704051617.59022.gary.stainburn@ringways.co.uk> MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Content-Disposition: inline Message-Id: <200704051703.04288.gary.stainburn@ringways.co.uk> X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200704/78 X-Sequence-Number: 28078 I've managed to come up with a solution that works, and embellished it to give exactly what I want. create view availability_details as select aid, asid, asdate, afdate, adays, count(rsgid) as allocated, adays-count(rsgid) as afree from ( select aid, asid, asdate, afdate, coalesce(adays,afdate-asdate+1) as adays, rsgid from availability a left join roster_staff r on r.rsdate >= a.asdate and r.rsdate <= a.afdate ) as list group by aid, asid, asdate, afdate, adays order by asid, asdate; select * from availability_details ; aid | asid | asdate | afdate | adays | allocated | afree -----+------+------------+------------+-------+-----------+------- 8 | 1 | 2007-03-29 | 2007-04-04 | 7 | 1 | 6 4 | 1 | 2007-04-06 | 2007-04-09 | 4 | 0 | 4 5 | 1 | 2007-04-14 | 2007-04-15 | 2 | 2 | 0 6 | 1 | 2007-04-21 | 2007-04-22 | 2 | 0 | 2 1 | 28 | 2007-03-01 | 2007-03-01 | 1 | 0 | 1 2 | 28 | 2007-03-02 | 2007-03-07 | 6 | 0 | 6 (6 rows) -- Gary Stainburn This email does not contain private or confidential material as it may be snooped on by interested government parties for unknown and undisclosed purposes - Regulation of Investigatory Powers Act, 2000