【问题标题】:A function calculating average age in years in SQL [postgresql]在 SQL [postgresql] 中计算平均年龄的函数
【发布时间】: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


【解决方案1】:

如果您要从人员表中查找平均年龄,则可以简单得多。对于初学者来说是这样的:

 SELECT AVG(AGE(dateofbirth)) 
   FROM person 

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 2014-10-17
    • 2020-07-26
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2021-12-23
    相关资源
    最近更新 更多