简体   繁体   中英

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 ValA ValB ValC Vald
1 4 2 1 NULL
2 11 1 5 6
3 2 NULL 1 8
4 NULL 3 2 NULL

I need a new table like

id Typ
1 A
2 C
3 B
4 D

my idea was to make a case when statement in the select like:

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. But you seem to want to treat those as 0 or -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
     );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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