postgresql整数数组的总和和长度?

时间:2015-01-27 05:05:22

标签: arrays postgresql

我试图对postgresql数组的内容求和,并确定其长度。在所有情况下,我正在使用整数数组类型的列。

ERROR:  function sum(integer[]) does not exist
LINE 1: select sum(interested) from deals;
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
db5=> select SUM(interested) from deals;
ERROR:  function sum(integer[]) does not exist
LINE 1: select SUM(interested) from deals;
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
db5=> select array_length(interested) from deals;
ERROR:  function array_length(integer[]) does not exist
LINE 1: select array_length(interested) from deals;
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
db5=>

与我读过的内容相反(Select sum of an array column in PostgreSQLhttp://www.postgresql.org/docs/8.4/static/functions-array.html)sum(列)和array_length(列,1)似乎没有像我预期的那样执行。我在查看错误的文档吗?如何获得postgre整数数组的总和和长度?

另外,这些是我和pg_query一起使用的php查询来运行这些调用:

$query = "UPDATE deals set remaining = max  - array_length(interested, 1), until = min -array_length(interested, 1";
$query = "UPDATE deals set remaining = max - (SELECT SUM FROM UNNEST(hours)), until = min - (SELECT SUM FROM UNNEST(hours))";

我修改了它们以考虑到评论中的Patrick的建议,但我仍然遇到语法错误,例如。

Warning: pg_query(): Query failed: ERROR: syntax error at end of input LINE 1: ...ngth(interested, 1), until = min -array_length(interested, 1 ^ in /var/www/html/join.php on line 162

谢谢。

1 个答案:

答案 0 :(得分:1)

在更新语句中,您忘记了语句末尾的括号(请参阅注释)。

在第二个更新语句中,您不能在UPDATE中使用sum,因为更新中不允许使用聚合函数。 使用自定义sql函数,该函数对数组中的所有元素求和并在更新中使用它:

CREATE FUNCTION array_sum(NUMERIC[]) returns numeric AS 
$$
  SELECT sum(unnest) FROM (select unnest($1)) as foo;
$$
LANGUAGE sql;

更新声明:

UPDATE deals SET remaining = max -  array_sum(hours), until = min - array_sum(hours);