在postgresql中,我如何计算只有一岁出生的人的年龄(将是一个估计值)——特别是想要得到最年轻的人和他们的年龄

在postgresql中,我如何计算只有一岁出生的人的年龄(将是一个估计值)——特别是想要得到最年轻的人和他们的年龄,postgresql,Postgresql,我知道有一个公式使用年龄(生日),但是如果我只有年份呢?这对你有用吗 CREATE TABLE people ( id integer NOT NULL, name text NOT NULL, year_born public.yeartype, year_died public.yeartype 假设您的public.yeartype可以更改为文本,那么这也许可以: select round(((current_date - to_date('2000','yyyy')) / 365.2

我知道有一个公式使用年龄(生日),但是如果我只有年份呢?

这对你有用吗

CREATE TABLE people (
id integer NOT NULL,
name text NOT NULL,
year_born public.yeartype,
year_died public.yeartype
假设您的
public.yeartype
可以更改为文本,那么这也许可以:

select round(((current_date - to_date('2000','yyyy'))  / 365.25)-1,0)

result: 20

你有两个信息面:出生年份和死亡年份,但不清楚你是在寻找仍然活着的最年轻的人还是一个人达到的最年轻的年龄,而不管他的生活状况如何。无论哪种方式,都可能会发生冲突(即,多人在同一年出生,并且与给定的出生年份相比缺乏精确性)。您可能会使用返回的第一条匹配记录(可能受其他条件的影响)或使用冲突列表

注意:对于这两种情况,将出生年份和死亡年份转换为时间戳,并对其使用提取,如果不可行,则使用提取结果(从现在开始的年份())对出生年份和死亡年份进行标准化,强制转换为双精度

返回最年轻的活着的人

select round(((current_date - to_date(year_born::text,'yyyy'))  / 365.25)-1,0)
where year_died IS NULL
select 
  name,
  (extract(year from now()) 
    - extract(year from year_born::timestamp)) as age

from people
-- where some other filter criteria 
order by age  -- put our youngest person/people at the top
limit 1       -- return only the top most row .. remove to return 
              -- all colliding 'youngest' ages
;
返回年龄最短的生者或死者

select round(((current_date - to_date(year_born::text,'yyyy'))  / 365.25)-1,0)
where year_died IS NULL
select 
  name,
  (extract(year from now()) 
    - extract(year from year_born::timestamp)) as age

from people
-- where some other filter criteria 
order by age  -- put our youngest person/people at the top
limit 1       -- return only the top most row .. remove to return 
              -- all colliding 'youngest' ages
;

你想知道他们活了多长时间?或者如果他们现在没有死,他们多大了?或者只想知道他们还活着多大了?你不能使用像01-01、07-03或12-31这样的代孕月和日吗?@stickybit我真正需要的唯一年龄是数据库中最年轻的人的年龄。如果可以的话,我想避免使用代孕月和日。什么是代孕
public.yeartype
?数据看起来像什么,仅仅是一个4位数的年份?@PaulMaxwell是的,确切地说,例如1996年