Received: from localhost (maia-2.hub.org [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id 011949FBC5B for ; Thu, 15 Mar 2007 12:51:49 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.187]) (amavisd-new, port 10024) with ESMTP id 55141-07 for ; Thu, 15 Mar 2007 12:51:39 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.4 Received: from zebedee.cranntara.net (zebedee.cranntara.net [91.186.7.79]) by postgresql.org (Postfix) with ESMTP id 74D9C9FBA84 for ; Thu, 15 Mar 2007 12:51:40 -0300 (ADT) Received: from du-005-0050.freeuk.com ([212.126.146.50] helo=bolek.coachhouse) by zebedee.cranntara.net with esmtpsa (TLS-1.0:RSA_AES_256_CBC_SHA1:32) (Exim 4.62) (envelope-from ) id 1HRsEq-0007pu-Is for pgsql-sql@postgresql.org; Thu, 15 Mar 2007 15:51:38 +0000 Received: from [192.168.0.32] (helo=[192.168.0.32]) by bolek.coachhouse with esmtp (Exim 4.50) id 1HRs8a-0007jK-F4 for pgsql-sql@postgresql.org; Thu, 15 Mar 2007 15:45:08 +0000 Message-ID: <45F96A04.7020307@numerixtechnology.de> Date: Thu, 15 Mar 2007 15:45:08 +0000 From: T E Schmitz Reply-To: pgsql-sql@postgresql.org User-Agent: Debian Thunderbird 1.0.7 (X11/20051017) X-Accept-Language: en-us, en MIME-Version: 1.0 To: pgsql-sql@postgresql.org Subject: join table with itself? Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200703/213 X-Sequence-Number: 27851 I am not getting to grips with the following query: set-up: Postgresql 8.1 The table HISTORY contains stockmarket data: DAY HIGH LOW 2007/02/28 6286.1 6166.2 2007/02/27 6434.7 6270.5 2007/02/26 6446.8 6401.5 I'd like to produce the following result: DAY HIGH LOW DAYS2FALL HIGHEST where DAYS2FALL is the number of days it takes for LOW to fall below the present row's LOW where HIGHEST is the highest HIGH during that period. I had a stab at DAYS2FALL: SELECT present.day, present.low, (MIN(future.day)-present.day) as days2fall FROM history AS present,history AS future WHERE present.day < future.day AND future.low <= present.low GROUP BY present.day,present.low ORDER BY days2fall DESC but didn't manage to express HIGHEST. Also, my attempt isn't exactly the fastest. -- Regards, Tarlika Elisabeth Schmitz