将数值赋给 varchar 后对一行的值求和

Sum values of a row after giving a numeric value to a varchar

我有两个 table,table_atable_b,如下所示。

Table 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 table_b:

  b_id |columna_fk|average
--------------------------
|   1  |  a       |
|   1  |  b       |
|   3  |  c       |

如何获取行的平均值(忽略 n/a)并更新 table_b 中的平均列?

例如见下面的table:

  b_id |columna_fk|average
--------------------------
|   1  |  a       | 1.5
|   1  |  b       | 3
|   3  |  c       | 2

一种方法是暴力破解:

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;

感谢您的回答,我做了一些改动,它对我有用。下面是我的零钱。

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;