avi
avi

Reputation: 1846

How to get one row per group in PostgreSQL?

I have the following data:

customerid addressid
939          936
939          35485
1915         2224
1915         34236
6005         7012
6005         27914

given by this query:

select customerid ,addressid
from addresses
where .....

I want the query to return only one address per customer, I don't care which address it will be. So the desiered output can be:

addressid
936
2224
7012

or

addressid
936
34236
7012

etc..

I tried to do:

select DISTINCT customerid ,addressid
from addresses
where .....

but it did nothing... I thought of doing GROUP BY customerid but then I'm losing the addressid. How can I do that?

Upvotes: 1

Views: 48

Answers (2)

user330315
user330315

Reputation:

If you don't care which addressid it is, this is a simple group by:

select customerid, max(addressid) as addressid
from addresses
group by customerid

Upvotes: 2

juergen d
juergen d

Reputation: 204746

Group by customerid and since it can be any address use a aggegation function like max() get the hghest

select customerid, max(addressid)
from addresses
group by customerid 

Upvotes: 2

Related Questions