1

I have the following scheme:

id | name | price | site_id | agency

1 | NAME | PRICE | 1 | AGENCY1
2 | NAME | PRICE | 1 | AGENCY1
3 | NAME | PRICE | 1 | AGENCY2
4 | NAME | PRICE | 1 | AGENCY2
5 | NAME | PRICE | 2 | AGENCY1
6 | NAME | PRICE | 2 | AGENCY1
7 | NAME | PRICE | 2 | AGENCY1

I want to get the first row with a unique agency for each site_id.

For example, the query result for the above scheme is expected to be:

1 | NAME | PRICE | 1 | AGENCY1
3 | NAME | PRICE | 1 | AGENCY2
5 | NAME | PRICE | 2 | AGENCY1

I have tried to look for solutions with DISTINCT but couldn't figure it out.

2 Answers 2

3

In Postgres, you should use distinct on:

select distinct on (site_id, agency) t.*
from t
order by site_id, agency, id;

Not only is this the most concise method, but it usually has the best performance of possible methods. You want an index on (site_id, agency, id) for optimal performance.

Sign up to request clarification or add additional context in comments.

Comments

1

With row_number() window function:

select t.id, t.name, t.price, t.site_id, t.agency
from (
  select *, row_number() over (partition by site_id, agency order by id) rn
  from tablename
) t
where t.rn = 1

See the demo.
Results:

| id  | name | price | site_id | agency  |
| --- | ---- | ----- | ------- | ------- |
| 1   | NAME | PRICE | 1       | AGENCY1 |
| 3   | NAME | PRICE | 1       | AGENCY2 |
| 5   | NAME | PRICE | 2       | AGENCY1 |

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.