我有以下postgres表工作经验:
id | userId | experience | isCurrentWorkplace
1 | 1 | xyz | true
2 | 1 | abc | true
3 | 1 | wxy | false
4 | 2 | qwe | false
5 | 2 | xyz | true
6 | 3 | abc | true
我想获取唯一的userId以及isCurrentlyWorkplace设置为true的表的ID。由于每个用户可以拥有isCurrentWorkPlace为true的多个记录,因此我得到了重复的记录。
基本上,这是我想要的结果集:
id | userId | experience | isCurrentWorkplace
1 | 1 | xyz | true
5 | 2 | xyz | true
6 | 3 | abc | true
isCurrentWorkplace设置为true的每个用户的最新记录。
查询工作正常,并返回不同的userId:
select distinct ("userId") from "workExperiences" where "isCurrentWorkplace" = true;
但是当我也选择id时,我开始获得重复记录:
select distinct ("userId"), id from "workExperiences" where "isCurrentWorkplace" = true;
我该如何实现?
谢谢您的帮助!
答案 0 :(得分:0)
您可以尝试使用row_number()
select * from
(
select *, row_number() over(partition by userid order by id) as rn
from "workExperiences" where "isCurrentWorkplace" = true
) A where rn=1