[英]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:我的想法是在 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.