选择一个文本值而不是另一个

Choosing one text value over the other

我有一个 table 类似如下:

  store    manager      status         
    1       tim          good  
    2       anna         good
    3       ben          bad  
    4       tim          bad
    5       tim          ok  

我的目标是获得如下所需的输出。我想显示每个经理的状态。顺序偏好为 bad > ok > good。因此,如果一个经理(tim)有3个不同的store status,那么最终的status会取bad

    manager       status         
      tim          bad
      anna         good
      ben          bad  

我想不出一个创造性的解决方案来选择一个值而不是另一个值,所以如果有人能给我 suggestion/approach 如何解决这个问题,我将不胜感激。

一种方法是使用如下条件逻辑进行聚合:

select manager,
       coalesce(max(case when status = 'bad' then status end),
                max(case when status = 'ok' then status end),
                max(case when status = 'good' then status end)
               )
from t
group by manager;

您还可以使用 window 函数:

select t.*
from (select t.*,
             row_number() over (partition by manager
                                order by case status when 'bad'  then 1 when 'ok' then 2 when 'good' then 3 else 4 end
                               ) as seqnum
      from t
     ) t
where seqnum = 1;