This is a query which selects a set of desired rows:
select max(a), b, c, d, e
from T
group by b, c, d, e;
The table has a primary key, in column id.
I would like to identify these rows in a further query, by getting the primary key from each of those rows. How would I do that? This does not work:
select id, max(a), b, c, d, e
from T
group by b, c, d, e;
ERROR: column "T.id" must appear in the GROUP BY clause or be used in an aggregate function
I have tried this from poking around in some other postgresql questions, but no luck:
select distinct on (id) id, max(a), b, c, d, e
from T
group by b, c, d, e;
ERROR: column "T.id" must appear in the GROUP BY clause or be used in an aggregate function
What do I do? I know there can only be one id for each result, cause it’s a primary key… I literally want the primary key along with the rest of the data, for each row that the initial (working) query returns.
If you don’t care which
idyou get then you just need to wrap youridin some aggregate function that is guaranteed to give you a validid. Themaxandminaggregates come to mind:Depending on your data I think using a window function would be a better plan (thanks to evil otto for the boot to the head):