Re: include ids in query grouped by multipe values

From: Carlos Chapi <carlos(dot)chapi(at)2ndquadrant(dot)com>
To: karsten(at)terragis(dot)net
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: include ids in query grouped by multipe values
Date: 2014-02-17 21:49:49
Message-ID: CAAk_w-pRO6uZ5c=s3RRuGOyfjCEX2y-QRqwTGf3pF+tcopNMRg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hi Karsten

2014-02-17 14:49 GMT-05:00 karsten <karsten(at)terragis(dot)net>:

>
> but that returns too many rows and I do not understand why
>

It returns more than the expected rows because there can be multiple rows
fulfilling the conditions (in the example, rows with id 6 and 7 will both
appear as both have the max(sale) for idone = 020 and idtwo = 230)

> How can I resolve this ?
>
>

It depends if you want to show all the rows with max(sale) (which you're
already doing so I suppose you don't want that), if you want to show the
first one to be found or if you want to show the last one to be found.

If you only want the first one, you could do something like:

SELECT min(a.id) as 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 a.IDtwo = b.IDtwo
AND a.sale = b.maxsale
GROUP BY a.IDone, a.IDtwo, a.sale;

and add the other columns as desired

--
Carlos Chapi
http://www.2ndQuadrant.com/<http://www.2ndquadrant.com/>
Professional PostgreSQL: Soporte 24x7 y capacitación

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message David Johnston 2014-02-17 22:12:41 Re: include ids in query grouped by multipe values
Previous Message karsten 2014-02-17 19:49:38 include ids in query grouped by multipe values