PostgreSQL - 为每个关系查找 N 个最新行

问题描述 投票:0回答:1

line
表行与许多
line_version
表行相关。我只需要为每个
line
行找到 N(比方说 2)最新行。

例如,这就是

line_version
表格行的样子(
line_id
line
表格相关):

  id   | line_id 
-------+---------
 10    |   1
 20    |   1
 30    |   1
 40    |   1
 50    |   2
 60    |   2
 70    |   2

因此,如果我们需要为每个

line_version
行查找 2 个最新
line
行 ID,则应该是
(30, 40, 60, 70)

在全球范围内,我只需执行以下操作即可获得 2 个最新的:

SELECT id from line_version ORDER BY id DESC limit 2

但是我该如何根据

line_id
关系做到这一点?

附注这里最新的意思是最大的ID。

sql postgresql
1个回答
0
投票

您可以使用以下

with data as (select 

     10 id   ,  1 line_id union all
     select 20    ,   1 union all
     select 30    ,   1 union all
     select 40    ,   1 union all
     select 50    ,  2 union all
     select 60    ,   2 union all
    select  70    ,   2),
    subset as (select a.*,ROW_NUMBER() over(partition by line_id order by id ) rownumber,count(id) over(partition by line_id) count1 from data a)
    select id,line_id from subset where rownumber=count1 or rownumber=count1-1;
© www.soinside.com 2019 - 2024. All rights reserved.