1

Having this table:

warehouse_id destination_id days
1 1 2
1 1 3
2 1 3
2 1 4
3 1 5
3 2 5
1 2 2
2 2 3

I'd like to get the warehouse_id and days for each value of warehouse_id, where the row has the minimum value of days, and destination_id matches a specific value, ordered by days.

For example for destination_id = 1

warehouse_id days
1 2
2 3
3 5
Erwin Brandstetter
187k28 gold badges467 silver badges644 bronze badges
asked Mar 1, 2021 at 4:38
2

2 Answers 2

3

Here is the query which orders by first for warehouse_id and days then gets first record only according to DISTINCT ON clause

select distinct on (warehouse_id) 
 warehouse_id,
 days 
 from this_table 
 where destination_id = 1 
 order by warehouse_id, days 
warehouse_id | days
-----------: | ---:
 1 | 2
 2 | 3
 3 | 5

db<>fiddle here

answered Mar 1, 2021 at 9:42
0
0

A simple aggregation like

select warehouse_id, min(days)
from this_table
where destination_id = 1
group by warehouse_id;

gives the answer in the question.

answered Mar 4, 2021 at 8:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.