pg.ddx.io  pgsql-performance@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Alvaro Herrera <alvherre@commandprompt.com>
To: Matthew Wakeling <matthew@flymine.org>
Cc: pgsql-performance <pgsql-performance@postgresql.org>
Subject: Re: Sorted group by
Date: Wed, 11 Aug 2010 11:54:17 -0400
Message-ID: <1281541760-sup-2001@alvh.no-ip.org> (raw)
In-Reply-To: <alpine.DEB.2.00.1008101627440.2654@aragorn.flymine.org>
References: <alpine.DEB.2.00.1008101627440.2654@aragorn.flymine.org>

Excerpts from Matthew Wakeling's message of mar ago 10 11:40:16 -0400 2010:

> I am trying to retrieve, for many sets of rows grouped on a couple of 
> fields, the value of an ungrouped field where the row has the highest 
> value in another ungrouped field.

I think this does what you want (schema is from the tenk1 table in the
regression database):

select string4 as group,
   (array_agg(stringu1 order by unique1 desc))[1] as value
from tenk1
group by 1 ;

Please let me know how it performs with your data.  The plan is rather simple:

regression=# explain analyze select string4 as group, (array_agg(stringu1 order by unique1 desc))[1] as value from tenk1 group by 1 ;
                                                          QUERY PLAN                                                           
───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 GroupAggregate  (cost=0.00..1685.16 rows=4 width=132) (actual time=22.825..88.922 rows=4 loops=1)
   ->  Index Scan using ts4 on tenk1  (cost=0.00..1635.11 rows=10000 width=132) (actual time=0.135..33.188 rows=10000 loops=1)
 Total runtime: 89.348 ms
(3 filas)


-- 
Álvaro Herrera <alvherre@commandprompt.com>
The PostgreSQL Company - Command Prompt, Inc.
PostgreSQL Replication, Consulting, Custom Development, 24x7 support



view thread (11+ messages)

Message-ID: <1281541760-sup-2001@alvh.no-ip.org>
Permalink:  ../1281541760-sup-2001@alvh.no-ip.org/
Also on:    postgresql.org/message-id/1281541760-sup-2001@alvh.no-ip.org

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-performance@postgresql.org
  Cc: alvherre@commandprompt.com, matthew@flymine.org
  Subject: Re: Sorted group by
  In-Reply-To: <1281541760-sup-2001@alvh.no-ip.org>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox