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 468183A3E73 for ; Thu, 4 Nov 2004 17:34:46 +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 49386-06 for ; Thu, 4 Nov 2004 17:34:44 +0000 (GMT) Received: from happy.onesystem.ca (happy.onesystem.ca [205.206.61.17]) by svr1.postgresql.org (Postfix) with ESMTP id BD8BB3A48A3 for ; Thu, 4 Nov 2004 17:34:43 +0000 (GMT) Received: from elb_lx.onesystem.ca ([10.1.1.50]) by happy.onesystem.ca with asmtp (Exim 4.14) id 1CPlVS-0004vc-6Q for pgsql-sql@postgresql.org; Thu, 04 Nov 2004 10:34:42 -0700 Message-ID: <418A6831.9060306@onesystem.com> Date: Thu, 04 Nov 2004 10:34:41 -0700 From: Edmund Bacon User-Agent: Mozilla Thunderbird 0.8 (X11/20040913) X-Accept-Language: en-us, en MIME-Version: 1.0 To: pgsql-sql@postgresql.org Subject: Re: Group by and aggregates References: <20041104165430.GD94770@mich2.itxmarket.com> In-Reply-To: <20041104165430.GD94770@mich2.itxmarket.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed 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/37 X-Sequence-Number: 19356 Michael L. Hostbaek wrote: > List, > > I've got a table looking something like this: > > my_table > some_id int bla bla, > partno varchar(100), > status varchar(100), > cmup numeric(14,2), > qty int > > My SQL select statement will then group together partno, status and > aggregate sum(qty) and max(cmup). This is all good and nice. > > 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 ? > You *CAN* sort by aggregates e.g. select partno, status, sum(cmup) as cmup, sum(qty) as qty from my_table group by partno, status order by partno, sum(cmup) desc; partno | status | cmup | qty --------+----------+------+----- test1 | incoming | 29 | 71 test1 | stock | 10 | 15 test2 | incoming | 12 | 10 -- Edmund Bacon