【问题标题】:Postgres - page by groupPostgres - 按组分页
【发布时间】:2016-09-05 19:19:49
【问题描述】:

假设我有一些数据:

id  |                stage | name
----+----------------------+------
  1 |          pyramid     | act 1
  2 |          pyramid     | act 2
  3 |          pyramid     | act 3
  4 |          other stage | act 4
  5 |          other stage | act 5
  6 |          other stage | act 6
  7 |          other stage | act 7
  8 |          shangri la  | act 8

我想使用分页将该数据加载到我的 UI 中 - 但我希望分页在组而不是行数上工作 - 实现这一目标的最佳方法是什么?

所以第 1 页(如果按 section_id 分组)将产生:

  1 |          pyramid | act 1
  2 |          pyramid | act 2
  3 |          pyramid | act 3

【问题讨论】:

  • 您希望它是动态的还是 section_id 是连续的,没有间隙?
  • 如果是,就只有where section_id=$page_number,$page_number作为参数来
  • 抱歉,这只是我从另一个随机帖子中复制的数据。恐怕没有顺序的section_id。我需要分页的数据也是一大块Sql的结果。
  • 我想我需要的是能够为组分配序列号...
  • 我更新了样本数据以更好地反映我的情况@JakubKania

标签: sql postgresql pagination


【解决方案1】:

如果您可以准确地指定您想要的条件,那么只需在 WHERE 子句中使用过滤器:

select *
from data
where stage = 'pyramid';

否则,如果您需要页码,则需要确定分组条件的排名。你可以这样做:

select *
from data
where stage = (
  select stage
  from (
    select stage, row_number() over ()
    from data
    group by stage
    order by stage
    ) s
  where row_number = <page number>
  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 2012-01-24
    相关资源
    最近更新 更多