用SQL计算平均年龄的函数[postgresql]

时间:2014-04-22 18:29:37

标签: sql postgresql average plpgsql pgadmin

我正在尝试创建一个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。

谢谢。

1 个答案:

答案 0 :(得分:7)

如果您正在寻找人员表的平均年龄,您可以更简单地做到这一点。这对初学者来说是这样的:

 SELECT AVG(AGE(dateofbirth)) 
   FROM person