PostgreSQL:条件基于两列的案例

PostgreSQL: Case with conditions based on two columns

想象一下虚拟数据

id   name     category    score   
1    Alex     A           11        
2    Alex     D           4      
3    Bill     A           81     
4    Bill     B           34       
5    Bill     D           2       
6    Carl     C           5       
7    Carl     D           10       

我要申请操作:

if score of A, B, or C > score of D
then 'Review'
else 'Pass'

所以输出是:

id   name     category    score   conclusion
1    Alex     A           11       Review
2    Alex     D           4        Review
3    Bill     A           81       Review
4    Bill     B           34       Review
5    Bill     D           2        Review
6    Carl     C           5        Pass
7    Carl     D           10       Pass

如何在 PostgreSQL 中获取它?

您想要使用 window 函数进行条件聚合:

select
  id, name, category, score,
  case when 
         max(score) filter (where category in ('A', 'B', 'C')) over (partition by name) >
         min(score) filter (where category = 'D')              over (partition by name)
       then 'Review'
       else 'Pass'
  end as result
from mytable
order by name, id;

如果名字没有A、B、C或名字没有D,结果会是'Pass'。如果您想要不同的方式,则必须调整 camparison。

以上查询为您提供了每个人的所有行中显示的状态。如果您希望每行有不同的状态,只需与该行的分数进行比较:

select
  id, name, category, score,
  case 
    when category = 'D' then null
    when score > min(score) filter (where category = 'D') over (partition by name) then 'Review'
    else 'Pass'
  end as result
from mytable
order by name, id;