1

I have the following table:

pk_positions    ass_pos_id   underlying   entry_date
1               1            abc          2016-03-14
2               1            xyz          2016-03-17
3                            tlt          2016-03-18
4               4            ujf          2016-03-21
5               4            dks          2016-03-23
6               4            dqp          2016-03-26

I need to select one row per ass_pos_id which has the earliest entry_date. Rows which do not have a value for ass_pos_id are not included.

In other words, for each non null ass_pos_id group, select the row which has the earliest entry_date

The following is the desired result:

pk_positions    ass_pos_id   underlying   entry_date
1               1            abc          2016-03-14
4               4            ujf          2016-03-21
2
  • what if there are 2 rows for a given ass_pos_id that have the same earliest entry date? Commented Apr 14, 2016 at 16:09
  • hi. The nature of the application that uses this data ensures that this scenario will never happen. ie: this is taken care of outside of the database. thanks. Commented Apr 14, 2016 at 16:15

1 Answer 1

1

You could use the row_number window function:

SELECT pk_positions, ass_pos_id, underlying, entry_date
FROM   (SELECT pk_positions, ass_pos_id, underlying, entry_date,
               ROW_NUMBER() OVER (PARTITION BY ass_pos_id
                                  ORDER BY entry_date ASC) rn
        FROM   mytable
        WHERE  ass_pos_id IS NOT NULL) t
WHERE   rn = 1
Sign up to request clarification or add additional context in comments.

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.