Re: include ids in query grouped by multipe values

Поиск
Список
Период
Сортировка
От David Johnston
Тема Re: include ids in query grouped by multipe values
Дата
Msg-id 1392675161284-5792491.post@n5.nabble.com
обсуждение исходный текст
Ответ на include ids in query grouped by multipe values  ("karsten" <karsten@terragis.net>)
Список 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.



В списке pgsql-sql по дате отправления:

Предыдущее
От: Carlos Chapi
Дата:
Сообщение: Re: include ids in query grouped by multipe values
Следующее
От: AlexK
Дата:
Сообщение: How to unnest an array with element indexes