我有一个表格,如下所示,我想选择u_id
与类型,但如果有更多的记录u_id
那么我想获得有best
类型的记录,或者如果它不存在然后good
等,best>good>worst
到目前为止。我只能得到返回的u_id
的第一行。根据列值选择记录
u_id type
1 best
2 good
3 worst
2 best
我有一个表格,如下所示,我想选择u_id
与类型,但如果有更多的记录u_id
那么我想获得有best
类型的记录,或者如果它不存在然后good
等,best>good>worst
到目前为止。我只能得到返回的u_id
的第一行。根据列值选择记录
u_id type
1 best
2 good
3 worst
2 best
您可以优先考虑row_number
,并为每个u_id选择一行。
select u_id,type
from (
select u_id,type,
row_number() over(partition by u_id order by case when type='best' then 1
when type='good' then 2
when type='worst' then 3
else 4 end) as rn
from tablename
) t
where rn=1
with type (n, type) as (values
(1, 'best'),(2,'good'),(3,'worst')
)
select distinct on (u_id) u_id, type
from t inner join type using (type)
order by u_id, n
感谢那些工作 – jemcaj