X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id AE3CF3A48CF for ; Thu, 4 Nov 2004 17:46:52 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 54375-05 for ; Thu, 4 Nov 2004 17:46:50 +0000 (GMT) Received: from anchor-post-35.mail.demon.net (anchor-post-35.mail.demon.net [194.217.242.85]) by svr1.postgresql.org (Postfix) with ESMTP id C4E583A488A for ; Thu, 4 Nov 2004 17:46:49 +0000 (GMT) Received: from mailgate.bray-healthcare.com ([80.177.250.202] helo=solport.bray-healthcare.com) by anchor-post-35.mail.demon.net with esmtp (Exim 4.42) id 1CPlh9-0005Pj-Ga; Thu, 04 Nov 2004 17:46:47 +0000 Received: from braydb.bray-healthcare.com ([192.168.1.18]) by solport.bray-healthcare.com with esmtp (Exim 3.36 #1 (Debian)) id 1CPlh9-0001gQ-00; Thu, 04 Nov 2004 17:46:47 +0000 Subject: Re: Group by and aggregates From: Oliver Elphick Reply-To: olly@lfix.co.uk To: "Michael L. Hostbaek" Cc: pgsql-sql@postgresql.org In-Reply-To: <20041104165430.GD94770@mich2.itxmarket.com> References: <20041104165430.GD94770@mich2.itxmarket.com> Content-Type: text/plain Message-Id: <1099590407.5445.24.camel@braydb> Mime-Version: 1.0 X-Mailer: Ximian Evolution 1.4.6 Date: Thu, 04 Nov 2004 17:46:47 +0000 Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.0 tagged_above=0.0 required=5.0 tests= X-Spam-Level: X-Archive-Number: 200411/40 X-Sequence-Number: 19359 On Thu, 2004-11-04 at 16:54, Michael L. Hostbaek wrote: ... > some_id partno status cmup qty > 1 test1 stock 10.00 15 > 2 test2 incoming 12.00 10 > 3 test1 incoming 15.00 60 > 4 test1 incoming 14.00 11 ... > My result will look something like this: > > partno status cmup qty > test1 stock 10.00 15 > test1 incoming 15.00 71 > test2 incoming 12.00 10 > > Now, I need the first line to say "15.00" in the cmup field. That is, > stock and incoming are obviously not being grouped, but since it's the > same partno I'd like somehow to show the highest cmup. Is there some > black SQL voodoo that'll achieve this ? junk=# select partno, status, (select max(cmup) from my_table as b where b.partno = a.partno) as cmup, sum(qty) from my_table as a group by partno, status, (select max(cmup) from my_table as b where b.partno = a.partno); partno | status | cmup | sum --------+----------+-------+----- test1 | incoming | 15.00 | 71 test1 | stock | 15.00 | 15 test2 | incoming | 12.00 | 10 (3 rows) Oliver Elphick