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

时间:2016-04-14 12:13:43

标签: sql postgresql postgresql-9.3 postgresql-9.2

我有两张表,table_atable_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

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;