从 table 获取记录?

Fetch record from table?

我有table其中的数据是这样的

映射关系

1 task_id 映射到多个 task_detail_id(1 到多个

Task_detail_id  Task_id    Creation_date
1                20         2020-05-02 20:28:23.354
2                21         2020-05-02 20:28:23.354
3                22         2020-05-02 19:28:23.354
4                22         2020-05-02 18:28:23.354
5                22         2020-05-02 17:28:23.354
6                22         2020-05-02 16:28:23.354
7                22         2020-05-02 15:28:23.354
8                23         2020-05-02 10:28:23.354
9                24         2020-05-02 09:28:23.354
10               24         2020-05-02 08:28:23.354
11               24         2020-05-02 07:28:23.354

我想要的是遍历 table 并获取记录,就好像 一样 task_id 存在超过 2 次,然后获取前 2 个(最新) task_id

的记录

示例输出

Task_detail_id  Task_id         Creation_date
1                 20            2020-05-02 20:28:23.354
2                 21            2020-05-02 20:28:23.354
3                 22            2020-05-02 19:28:23.354
4                 22            2020-05-02 18:28:23.354
8                 23            2020-05-02 10:28:23.354
9                 24            2020-05-02 09:28:23.354
10                24            2020-05-02 08:28:23.354

这通常使用 window 函数完成:

select task_detail_id, task_id, creation_date
from (
  select task_detail_id, task_id, creation_date, 
         row_number() over (partition by task_id order by creation_date desc) as rn
  from data
) t
where rn <= 2
order by task_detail_id, task_id;

Online example