从表中获取一组或多行

时间:2014-11-14 11:33:07

标签: sql oracle plsql

我有一张包含数据的表Exam_record。我需要知道如何根据latest exam date.

为每个EID提取最新的2条记录
EID | Exam_name | score | date_of_completion |
-----------------------------------------------
1   | Exam_1    | 60    | 23-Jun-2014        |
1   | Exam_1    | 70    | 10-Jan-2014        |
1   | Exam_1    | 71    | 15-Aug-2014        |
1   | Exam_1    | 65    | 1-Sep-2014         |
2   | Exam_2    | 50    | 2-Jul-2014         |
2   | Exam_2    | 55    | 12-May-2014        |
2   | Exam_2    | 65    | 15-Apr-2014        |

所需的输出

EID | Exam_name | score | date_of_completion |
-----------------------------------------------
1   | Exam_1    | 71    | 15-Aug-2014        |
1   | Exam_1    | 65    | 1-Sep-2014         |
2   | Exam_2    | 55    | 12-May-2014        |
2   | Exam_2    | 50    | 2-Jul-2014         |

1 个答案:

答案 0 :(得分:1)

试试这样:

select * from
(
select *,row_number()over(partition by EID order by  date_of_completion desc) as rn from table
)x
where x<=2

more info