【发布时间】:2016-03-21 23:04:03
【问题描述】:
我正在尝试在 postgre sql 中编写一个函数来取三列的平均值。我写了以下函数:
create function xcol_avg (col1, col2, col3)
returns numeric as $$
begin
return (coalesce(col1, 0) + coalesce(col2,0) +coalesce(col3, 0))/
case when (col 1 is null or col1 = 0 then 0 else 1 end +
case when (col 2 is null or col2 = 0 then 0 else 1 end +
case when (col 3 is null or col3 = 0 then 0 else 1 end;
end
我的代码有什么问题?另外,如果函数最终被0除,有没有办法让函数返回null?非常感谢任何帮助。 谢谢!
【问题讨论】:
-
你的问题到底是什么?
-
@Kristen,我已经添加了我的答案。希望这可以为您提供有关该主题的足够信息。您的功能存在各种问题。我建议您查看手册:postgresql.org/docs/current/static/sql-createfunction.html
标签: postgresql function average