假设我有两个表,posts 和 users,我想要的是选择每个用户的第二个帖子(每个帖子都有日期,所以我可以对其进行排序)。
我已经阅读了偏移量和限制,但它们都没有解决我的问题(至少没有我尝试过的方法)。我确实认为我正在寻找的是某种组功能,因为它需要在每个组(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”。
最佳答案
使用row_number
和子查询
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
关于sql - PostgreSQL - 如何选择组函数的每一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51864525/