【发布时间】:2014-04-22 18:29:37
【问题描述】:
我正在尝试创建一个 plpgsql 函数,该函数可以计算某些人的平均年龄(以年为单位),并将 ID(整数)存储在另一个表中。
代码是:
begin
DROP TABLE if EXISTS dates;
DROP TABLE if EXISTS tmp;
DROP TABLE if EXISTS ages;
CREATE TABLE ages (age integer);
--(...) In these lines, I create and fill the table tmp. I did not include this code
--since it's not very much related to my problem. Nevertheless, this table has only
--one integer column
CREATE TABLE dates AS (SELECT "dateofbirth" from person where "idPerson" in (select "bookedforpersonID" from personsofthistype));
UPDATE ages SET (age) = ((SELECT extract (year from age(dateofbirth)) from dates));
return (select avg(age) from age);
end;
当然,dateofbirth 的类型是 date。我的问题是创建的表年龄不包含任何内容,因此我无法返回正确的结果(其列的平均年龄)。该函数的返回类型是integer(并且在pgadmin中没有选择“返回集”)。
我使用的是 PostgreSQL 9.3.4,pgAdmin III 版本 1.18.1。
谢谢。
【问题讨论】:
-
这读起来太复杂了。您是否有一张包含生日的人的表格,并且只想要平均年龄?
标签: sql postgresql average plpgsql pgadmin