mgu*_*gus 4 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;
Run Code Online (Sandbox Code Playgroud)
当然,dateofbirth是类型date.我的问题是创建的表年龄不包含任何内容,因此我无法返回正确的结果(其列的平均年龄).函数的返回类型是integer(并且在pgadmin中未选择"返回集").
我正在使用PostgreSQL 9.3.4,pgAdmin III版本1.18.1.
谢谢.
如果您从perosn表中寻找平均年龄,您可以更简单地完成它.这对初学者来说是这样的:
SELECT AVG(AGE(dateofbirth))
FROM person
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4096 次 |
| 最近记录: |