首页 > 解决方案 > PostgreSQL - 如何选择组函数的每隔一行?

问题描述

假设我有两个表,帖子和用户,我想要的是选择每个用户的第二个帖子(每个帖子都有它的日期,所以我可以订购它)。

我已经阅读了有关偏移量和限制的信息,但是它们都没有解决我的问题(至少没有我尝试过的方式)。我确实认为我正在寻找的是某种组功能,因为它需要在每个组(1 个用户 - N 个帖子)中工作,而不仅仅是在最终输出中。

我正在使用内部连接来选择组合数据。

有人可以帮我吗?

桌子

user_id   post_id       date         post_name
  1          1       2018-01-01       post 1
  1          2       2018-02-02       post 2
  1          3       2018-03-03       post 3
  2          4       2018-01-01       post 1
  2          5       2018-02-02       post 2
  2          6       2018-03-03       post 3
  3          7       2018-01-01       post 1
  3          8       2018-02-02       post 2
  3          9       2018-03-03       post 3
  4          10      2018-03-03       post 1

预期结果

user_id   post_id       date         post_name
   1          2       2018-02-02       post 2
   2          5       2018-02-02       post 2
   3          8       2018-02-02       post 2
   4         null        null           null

**当用户没有第二个帖子时,必须设置值“null”。

标签: sqldatabasepostgresqljoin

解决方案


使用row_numbersub-query

select * from
(
select *,row_number() over(partition by user_id   order by date) as rn from tablea
) as t
where rn =2

http://www.sqlfiddle.com/#!15/3636a/2

根据输出我改变了我的查询

select * from
(
select *,row_number() over(partition by user_id   order by date) as rn from t
) as t
where rn =2
union
select t1.*,null,null,null,null from
(select user_id from t group by user_id having count(*)=1 ) as t1

http://sqlfiddle.com/#!15/ee032/6


推荐阅读