2017-02-27 157 views
0

我有一个表格,如下所示,我想选择u_id与类型,但如果有更多的记录u_id那么我想获得有best类型的记录,或者如果它不存在然后good等,best>good>worst到目前为止。我只能得到返回的u_id的第一行。根据列值选择记录

u_id type 
1 best 
2 good 
3 worst 
2 best 

回答

3

您可以优先考虑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 
+0

感谢那些工作 – jemcaj

2
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 
1

两个其他的答案是非常好的。这是对distinct on版本的变种,不需要join

select distinct on (u_id) u_id, type 
from t 
order by u_id, array_position(array[('best'), ('good'), ('worst')], type) 
+0

我已经使用了“接受的答案”的方法,但这个看起来最容易理解我。 – jemcaj

+0

我试图这样做,因为如果我在接受的答案中采用这种方法,则需要60倍的时间来获取我的数据。但是函数array_position在postgreSQL中不存在 – jemcaj