SQL 中前 2 列的平均值

Average of top 2 columns in SQL

我有一个 SQL 数据库,它有 3 个列,像这样

IA1    IA2    IA3

现在我需要找到三列(IA1、IA2 和 IA3)中前 2 个属性的平均值,并将该值存储在第三列中 FINAL_IA

目前第 FINAL_IA 列没有值。其他列的 None 包含空值,全部包含 integer 类型值。

例如,

IA1    IA2    IA3    FINAL_IA
-----------------------------
10     20     30
30     40     10

最后的table应该是,

IA1    IA2    IA3    FINAL_IA
-----------------------------
10     20     30     25
30     40     10     35

编辑 1

代码需要 运行 在 Linux 机器上 运行ning SQLPlus。 这就是 table ia 的创建方式,

create table ia (iid integer primary key, ia1 integer, ia2 integer, ia3 integer, finalia integer);

示例插入语句

insert into ia(iid, ia1, ia2, ia3) values (001, 30, 40, 10);

如果您提供一些基本脚本来创建初始状态(table、一些插入等)并提供 sql 您试图解决该问题的方言,会更容易。

但我们假设它是一个 Postgres,所以:

update t set final_ia = greatest(ia1 + ia2, ia2 + ia3, ia1 + ia3) / 2;

应该做一份工作。它从给定的计算表达式中取最大值,并使用它来更新最后一列。

假设值都不同,你可以使用一个巨大的 case 表达式:

select t.*,
       (case when ia1 < ia2 and ia1 < ia3 then (ia2 + ia3) / 2
             when ia2 < ia1 and ia2 < ia3 then (ia1 + ia3) / 2
             when ia3 < ia2 and ia3 < ia1 then (ia1 + ia2) / 2
        end)
from t;

在很多数据库中,有更简单的写法,比如:

select (ia1 + ia2 + ia3 - least(ia1, ia2, ia3)) / 2

编辑 在尝试代码后更改了第二种情况。