根据组

时间:2016-04-14 16:06:55

标签: sql postgresql select

我有下表:

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

我需要为ass_pos_id选择最早entry_date的一行。不包含ass_pos_id值的行。

换句话说,对于每个非空ass_pos_id组,请选择最早entry_date

的行

以下是期望的结果:

pk_positions    ass_pos_id   underlying   entry_date
1               1            abc          2016-03-14
4               4            ujf          2016-03-21

1 个答案:

答案 0 :(得分:1)

您可以使用row_number窗口函数:

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