sql - PostgreSQL - 如何选择组函数的每一行?

标签 sql database postgresql join

假设我有两个表,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

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

关于sql - PostgreSQL - 如何选择组函数的每一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51864525/

相关文章:

php - 如何在保持查询清晰有效的同时实现动态属性

mysql - 我应该使用多个查询或函数吗?

python - GAE 柔性环境 postgres 连接字符串?

python - sqlalchemy.exc.ArgumentError : Mapper mapped class could not assemble any primary key columns for mapped table 'users'

mysql - 数据库设计反馈

postgresql - 在表上插入或更新违反外键约束 PSQL/Knex

sql - 如何按国家/地区查询 PostGIS 中的数据?

sql - 用分隔符分隔字符串并分配给变量 - sql

sql - 如何在 SQL 查询中获得某些记录没有值的列

ruby-on-rails - 在 Rails 模型中添加公共(public)变量?