简体   繁体   English

PostgreSQL,按行值的情况

[英]PostgreSQL, case when by row values

for each row of the dataset i need to make a assignment with some criterion.对于数据集的每一行,我需要使用一些标准进行分配。 so for example:例如:

id ID ValA缬氨酸 ValB缬氨酸B ValC缬氨酸 Vald瓦尔德
1 1 4 4 2 2 1 1 NULL NULL
2 2 11 11 1 1 5 5 6 6
3 3 2 2 NULL NULL 1 1 8 8
4 4 NULL NULL 3 3 2 2 NULL NULL

I need a new table like我需要一张新桌子

id ID Typ类型
1 1 A一个
2 2 C C
3 3 B
4 4 D D

my idea was to make a case when statement in the select like:我的想法是在 select 中的声明如下:

case when ValA > ValB > "all other row values" then 'A'
     when ValD > ValA > "all other row values" then 'B'
     when ValA > ValD > "all other row values" then 'C' 
     else 'D'
end as Typ

Is there a way to assign something like this?有没有办法分配这样的东西?

The NULL values make this tricky. NULL值使这很棘手。 But you seem to want to treat those as 0 or -1 :但是您似乎想将它们视为0-1

select t.*,
       (case when vala > valb and
                  valb > coalesce(valc, -1) and
                  valb > coalesce(vald, -1) 
             then 'A'
             when vald > vala and
                  vala > coalesce(valb, -1) and
                  vala > coalesce(valc, -1) 
             then 'B'
             when vala > vald and
                  vald > coalesce(valb, -1) and
                  vald > coalesce(valc, -1) 
             then 'C'
             else 'D'
       end) as typ
from t;

If you just wanted the highest value in a column (which makes more sense to me), then you can use a lateral join:如果您只想要列中的最高值(这对我来说更有意义),那么您可以使用横向连接:

select t.*, v.typ
from t cross join lateral
     (select v.*
      from (values ('A', valA), ('B', valB), ('C', valC), ('D', valD)
           ) v(typ, val)
      where v.val is not null
      order by v.val desc
      limit 1
     );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM