sql - 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”。
解决方案
使用row_number
和sub-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
推荐阅读
- objective-c - 是否有任何最新资源可以解释 MacOS 的 AuthenticationPlugin 开发?
- spotfire - 甘特图,活动持续时间
- java - 用于 Spring Boot Web 应用程序的 Maven 构建插件
- python - 使用 psycopg2 时如何使用多行 f 字符串
- python - 与 Maya scriptJob 命令一起使用的事件是什么,以便跟踪何时从渲染层添加或删除对象?
- python-3.x - 如何创建一个只接受字符串值的空列表
- python - Pandas:按组 ID 逐行填充 NaN 值
- php - 如何使用 Psalm 的 UnusedMethod 功能?
- windows - 无法识别 Git Flow Init 命令 - 未找到命令
- python - 抓取交互式地图时如何放大元素?