sql group by statement
sql group by statement
От:
"Albrecht Berger" <berger1517@gmx.ch>
Дата:
Hello, I have a problem, which I'm not able to solve with a simple query : I need a resultset with distinct id's, but the max val2 of each id. I tried to group by id, but though I need the pk in my resultset I have to group it too, which "destroys" the group of val2. Can this be done without a huge query ? Table : pk id val1 val21 1 2 32 1 2 43 2 1 14 1 0 55 2 1 8 Needed Result : pk id val1 val24 1 0 55 2 1 8 Thx berger
Re: sql group by statement
От:
dima <_pppp@mail.ru>
Дата:
see the yesterday's thread about DISTINCT ON (non-standard Postgres feature) > I have a problem, which I'm not able to solve with a simple query : > > I need a resultset with distinct id's, but the max val2 of each id. > I tried to group by id, but though I need the pk in my resultset > I have to group it too, which "destroys" the group of val2.
Re: sql group by statement
От:
"Albrecht Berger" <berger1517@gmx.ch>
Дата:
but how do I know that "distinct on" doesn't cut off the row with max(val2) of that id that I need ? > see the yesterday's thread about DISTINCT ON (non-standard Postgres feature) > > > I have a problem, which I'm not able to solve with a simple query : > > > > I need a resultset with distinct id's, but the max val2 of each id. > > I tried to group by id, but though I need the pk in my resultset > > I have to group it too, which "destroys" the group of val2. > > >
Re: sql group by statement
От:
Manfred Koizar <mkoi-pg@aon.at>
Дата:
On Fri, 13 Sep 2002 12:29:21 +0200, "Albrecht Berger" wrote: >Table : >pk id val1 val2 > 1 1 2 3 > 2 1 2 4 > 3 2 1 1 > 4 1 0 5 > 5 2 1 8 > > >Needed Result : >pk id val1 val2 > 4 1 0 5 > 5 2 1 8 Albrecht, "DISTINCT ON eliminates rows that match on all the specified expressions, keeping only the first row of each set of duplicates." So the trick is to sort appropriately: SELECT DISTINCT on (id) pk, id, val1, val2 FROM yourtable ORDER BY id asc, val2 desc, pk desc; ServusManfred
Re: sql group by statement
От:
Jean-Luc Lachance <jllachan@nsd.ca>
Дата:
How about: select * from
Re: sql group by statement
От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
"Albrecht Berger" writes: > but how do I know that "distinct on" doesn't cut off > the row with max(val2) of that id that I need ? Because you do SELECT DISTINCT ON (id) ... ORDER BY id, val2 DESC; The DISTINCT keeps the first of each group of rows with the same id, and by virtue of the ORDER BY (which acts first) the max val2 will be the first row in that group. Note there's no GROUP BY in this approach. regards, tom lane