X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id C3F969DCBA3 for ; Sun, 12 Mar 2006 11:05:36 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 23109-03 for ; Sun, 12 Mar 2006 11:05:40 -0400 (AST) X-Greylist: delayed 01:00:00.538277 by SQLgrey- Received: from relais.videotron.ca (relais.videotron.ca [24.201.245.36]) by postgresql.org (Postfix) with ESMTP id 69F479DCB80 for ; Sun, 12 Mar 2006 11:05:33 -0400 (AST) Received: from lythanhphu ([66.130.233.129]) by VL-MH-MR002.ip.videotron.ca (Sun Java System Messaging Server 6.2-2.05 (built Apr 28 2005)) with ESMTP id <0IW0005WRPTDIA40@VL-MH-MR002.ip.videotron.ca> for pgsql-sql@postgresql.org; Sun, 12 Mar 2006 09:05:37 -0500 (EST) Date: Sun, 12 Mar 2006 09:05:37 -0500 From: Daniel CAUNE Subject: Re: pgsql aggregate: conditional max In-reply-to: <4413AD1C.9050604@indiana.edu> To: 'Weimao Ke' , pgsql-sql@postgresql.org Message-id: <0IW0005WSPTDIA40@VL-MH-MR002.ip.videotron.ca> MIME-version: 1.0 X-MIMEOLE: Produced By Microsoft MimeOLE V6.00.2900.2180 X-Mailer: Microsoft Office Outlook, Build 11.0.6353 Content-type: text/plain; charset=utf-8 Content-transfer-encoding: 7BIT Thread-index: AcZFk0b6FyArL1I0QPGWvB402QEinQASR5Bw X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=0.622 required=5 tests=[AWL=0.622] X-Spam-Score: 0.622 X-Spam-Level: X-Archive-Number: 200603/172 X-Sequence-Number: 24518 > Hi, > > I need a special aggregation function. For instance, given the following > table data: > > aid | cat | weight > ----------+---------+--------- > a1 | Drama | 1 > a1 | Romance | 6 > a1 | Short | 1 > a1 | Other | 7 > a2 | Comedy | 1 > a2 | Drama | 2 > a3 | Drama | 1 > a3 | Adult | 2 > a3 | Comedy | 1 > a3 | Other | 1 > > I want to group by "aid" and choose the category (i.e., "cat") with the > largest "weight": > > aid | max_weighted_cat > ----+--------------------- > a1 | Other > a2 | Drama > a3 | Adult > > Any ideas? Thank you! :) > SELECT aid, cat FROM table, ( SELECT aid, max(weight) as weight FROM table GROUP BY aid) AS tablemaxweight WHERE table.aid = tablemaxweight.aid AND table.weight = tablemaxweight.aid; There is a limit case you don't specify how to deal with, when two or more categories have the same maximum weight. The query I wrote retrieves all the categories that have the maximum weight, but perhaps you just want one per aid. -- Daniel