简体   繁体   English

Postgresql 查询根据 2 列过滤最新数据

[英]Postgresql query to filter latest data based on 2 columns

Table Structure First表结构优先

users table

id ID
1 1
2 2
3 3

sites table

id ID
1 1
2 2

site_memberships table

site_id site_id user_id用户身份 created_on创建于
1 1 1 1 1 1
1 1 1 1 2 2
1 1 1 1 3 3
2 2 1 1 1 1
2 2 1 1 2 2
1 1 2 2 2 2
1 1 2 2 3 3

Assuming higher the created_on number, latest the record假设 created_on 数字越高,最新的记录

Expected Output

site_id site_id user_id用户身份 created_on创建于
1 1 1 1 3 3
2 2 1 1 2 2
1 1 2 2 3 3

Expected output: I need latest record for each user for each site membership.预期 output:我需要每个站点成员的每个用户的最新记录。

Tried the following query, but this does not seem to work.尝试了以下查询,但这似乎不起作用。

select * from users inner join
      (
        SELECT ROW_NUMBER () OVER (
            PARTITION BY sm.user_id,
            sm.created_on
        ), sm.* 
            from site_memberships sm 
            inner join sites s on sm.site_id=s.id
            ) site_memberships
ON site_memberships.user_id  = users.user_id where row_number=1```

I think you have overcomplicated the problem you want to solve.我认为您将要解决的问题过于复杂化了。

You seem to want aggregation:你似乎想要聚合:

select site_id, user_id, max(created_on)
from site_memberships sm
group by site_id, user_id;

If you had additional columns that you wanted, you could use distinct on instead:如果您有其他想要的列,则可以使用distinct on代替:

select distinct on (site_id, user_id) sm.*
from site_memberships sm
order by site_id, user_id, created_on desc;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM