我有两张表,table_a
和table_b
,如下所示。
表table_a
:
a_id |columna |varchar1|varchar2|varchar3
----------------------------------
| 1 | a | Medium | High | n/a
| 2 | b | Low | n/a | n/a
| 3 | c | Medium | Low | High
在table_a
中,每个varchar值都有一个数值:
高为1,中为2,低为3。
表table_b
:
b_id |columna_fk|average
--------------------------
| 1 | a |
| 1 | b |
| 3 | c |
如何获取table_b
中行和更新平均列的平均值(忽略n / a)?
例如见下表:
b_id |columna_fk|average
--------------------------
| 1 | a | 1.5
| 1 | b | 3
| 3 | c | 2
答案 0 :(得分:1)
一种方法是蛮力:
update b
set average = ((case varchar1 when 'High' then 1 when 'Medium' then 2 when 'Low' then 3 end) +
(case varchar2 when 'High' then 1 when 'Medium' then 2 when 'Low' then 3 end) +
(case varchar3 when 'High' then 1 when 'Medium' then 2 when 'Low' then 3 end)
) /
nullif((case varchar1 when 'n/a' then 0 else 1 end) +
(case varchar2 when 'n/a' then 0 else 1 end) +
(case varchar3 when 'n/a' then 0 else 1 end)
)
from a
where a.columna = b.columna_fk;
答案 1 :(得分:0)
感谢您的回答,我做了一些改动,并且它为我工作。以下是我的改变。
update b
set average =
(case when
((case varchar1 when 'High' then 1 when 'Medium' then 2 when 'Low' then 3 else 0 end) +
(case varchar2 when 'High' then 1 when 'Medium' then 2 when 'Low' then 3 else 0 end) +
(case varchar3 when 'High' then 1 when 'Medium' then 2 when 'Low' then 3 else 0 end)) <> 0
then
((case varchar1 when 'High' then 1 when 'Medium' then 2 when 'Low' then 3 else 0 end) +
(case varchar2 when 'High' then 1 when 'Medium' then 2 when 'Low' then 3 else 0 end) +
(case varchar3 when 'High' then 1 when 'Medium' then 2 when 'Low' then 3 else 0 end))
/
((case varchar1 when 'n/a' then 0 else 1 end) +
(case varchar2 when 'n/a' then 0 else 1 end) +
(case varchar3 when 'n/a' then 0 else 1 end))
else null end)
from a where a.columna = b.columna_fk;