IF/ELSE 的 PSQL 平均值

PSQL average with IF/ELSE

我有一个 psql table,其中的列包括:年、值、...等等。

我想做这样的事情:

select 
CASE WHEN avg(value) >=0 then avg(value) 
     ELSE -999 
END
from my_table
where year >= 2000 and year < 2005 and value >= 0

所以我希望我的平均值忽略任何具有负值的年份,但是对于所有年份都具有负值的情况,我想 return -999。

此查询运行但不运行 return -999 在所有值为负的情况下。

你在 where 子句中给出了 value>=0 这只会计算非负值的平均值,因此你永远不会得到负值的平均值

where year >= 2000 and year < 2005 and value >= 0

猜猜你想做什么

    select 
    CASE WHEN value >=0 then 
    (select avg(value) from t_table where value>=0)
         ELSE -999 
    END
    from table
    where year >= 2000 and year < 2005;

如果我对你的理解正确,你正在寻找类似的东西:

select 
   coalesce(avg(value) filter (when value >= 0), -999)
from my_table
where year >= 2000 and year < 2005;

其中 returns -999 如果所有值为负 则有零行匹配 WHERE 子句。 avg returns 如果未获得任何输入行,则为 null。

filter 语法仅适用于较新的 PostgreSQL 版本。对于年龄较大的,您必须使用 avg(case when value >= 0 then value end).