Re: include ids in query grouped by multipe values

From: David Johnston <polobo(at)yahoo(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: include ids in query grouped by multipe values
Date: 2014-02-17 22:12:41
Message-ID: 1392675161284-5792491.post@n5.nabble.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Karsten-3-2 wrote
> select IDone, IDtwo, max(sale) as maxsale FROM TableA group by IDone,
> IDtwo;
>
> But it would want to also select the id column ( and all other additonal
> 20
> columns of TabelA not shown above) and need that there is only one record
> returned for each IDone - IDtwo combination. I tried
>
> SELECT a.id, a.IDone, a.IDtwo, a.sale FROM TableA a
> inner join ( select IDone, IDtwo, max(sale) as maxsale FROM TableA group
> by
> IDone, IDtwo ) b
> on a.IDone = b.IDone and b.IDtwo = b.IDtwo
> and a.sale = b.maxsale;
>

[Not Tested]

SELECT b.IDone, b.IDtwo, b.sale, array_agg(a) AS matching_on_tableA
FROM TableA a
NATURAL JOIN ( SELECT IDone, IDtwo, max(sale) AS sale FROM TableA GROUP BY
1, 2 ) b
GROUP BY 1, 2, 3;

In this solution you simply save the entire tableA record, as a composite
typed column, into an array so that you now have a single row for each
"IDone, IDtwo, (max)sale" combination - which you omitted in the description
above - but can still access to relevant matching rows using the array. Add
"ORDER BY" - e.g., array_agg(...ORDER BY) - to setup a desired sort order.
You can do something like (against, not tested):

SELECT IDone, IDtwo, sale, (array_agg[0]).* AS row_from_tablea FROM <the
above query>

to get to the relevant data in the array.

David J.

--
View this message in context: http://postgresql.1045698.n5.nabble.com/include-ids-in-query-grouped-by-multipe-values-tp5792470p5792491.html
Sent from the PostgreSQL - sql mailing list archive at Nabble.com.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message AlexK 2014-02-19 19:25:56 How to unnest an array with element indexes
Previous Message Carlos Chapi 2014-02-17 21:49:49 Re: include ids in query grouped by multipe values