带窗口功能的分页

时间:2019-04-17 03:35:39

标签: sql postgresql

假设每个个人资料都有一个电子邮件地址,我试图对以上个人资料进行分页。我想获取用户的最新电子邮件地址(当前地址)。由于某种原因,最新的电子邮件不是第一个查询中返回的唯一电子邮件,而第二个是正确的。

select distinct ON (email) email, count(*) over()
from "profile" 
where "email" = 'example@test.com' 
order by "email" desc, "created_date" desc limit 1

返回:

email             | count
------------------+------
example@test.com  |    18
select distinct ON (email) email
from "profile" 
where "email" = 'example@test.com' 
order by "email" desc, "created_date" desc limit 10

返回:

email
----------------
example@test.com

1 个答案:

答案 0 :(得分:0)

如果要在获取分页列表时避免重复代码,并且无论页面大小如何,整个列表的计数都可以,请使用CTE

-- unpaged
with source as
(
    select distinct on (email)
         *
    from profile
    order by email desc, created_date desc
)
, paged as
(
    select *
    from source
    offset ((p_pageNumber - 1) * p_pageSize)
    limit p_pageSize
)
, all_count_and_paged_list as
(
    select
        (select json_agg(p.*) from paged p) as list,
        (select count(*) from source) as all_count
)
select row_to_json(r.*) from all_count_and_paged_list r

如果您要计算p_pageSize提取的实际行数,请获取page_count:

, all_count_and_paged_list as
(
    select
        (select json_agg(p.*) from paged p) as list,
        (select count(p.*) from paged p) as page_count,
        (select count(*) from source) as all_count
)