Sql 显示前N个组

Sql 显示前N个组,sql,postgresql,Sql,Postgresql,模式 在下文中,此表的排序是按有效时间进行的 查询结果 身份证件 类型 工业贸易署 数量 有效的 1. 无效的 无效的 2 2020-01-01T20:00:00.000Z 2. 修订版 1. 2 2020-01-01T20:00:01.000Z 3. 身体 1. 2 2020-01-01T20:00:02.000Z 4. 无效的 无效的 2 2020-01-01T20:00:02.000Z 5. 修订版 2. 2 2020-01-01T20:00:02.000Z 6. 身体 2. 2 2020

模式

在下文中,此表的排序是按有效时间进行的

查询结果

身份证件 类型 工业贸易署 数量 有效的 1. 无效的 无效的 2 2020-01-01T20:00:00.000Z 2. 修订版 1. 2 2020-01-01T20:00:01.000Z 3. 身体 1. 2 2020-01-01T20:00:02.000Z 4. 无效的 无效的 2 2020-01-01T20:00:02.000Z 5. 修订版 2. 2 2020-01-01T20:00:02.000Z 6. 身体 2. 2 2020-01-01T20:00:02.000Z 7. 身体 3. 2 2020-01-01T20:00:03.000Z
您可以枚举这些组。我的建议是使用滞后,然后使用累积总和:

select t.*
from (select t.*,
             sum(case when prev_tid = tid then 0 else 1 end) over (order by id) as grp
      from (select t.*,
                   lag(tid) over (order by id) as prev_tid
            from test t
           ) t
      ) t
where grp <= 3;
他是一把小提琴

select * from test order by effective_at;
select t.*
from (select t.*,
             sum(case when prev_tid = tid then 0 else 1 end) over (order by id) as grp
      from (select t.*,
                   lag(tid) over (order by id) as prev_tid
            from test t
           ) t
      ) t
where grp <= 3;