PostgreSQL日期类型的年龄计算

16

我有以下表格:

CREATE TABLE public.employees
(
employee_id integer NOT NULL,
name text NOT NULL,
date_of_birth date,
address text,
email text,
CONSTRAINT employees_pkey PRIMARY KEY (employees_id),
CONSTRAINT employees_email_key UNIQUE (email)
)
我怎样才能够将每个雇员的姓名和年龄列在输出中?谢谢。

3
有一个年龄函数,通过传递参数计算年龄。选择员工ID、姓名和age(date_of_birth)(即使用出生日期计算的年龄)从员工表中查询。 - Fahad Anjum
age() 函数的文档在这里:https://www.postgresql.org/docs/current/static/functions-datetime.html - user330315
2个回答

30

谢谢,我只是对date_part感到困惑,但你帮助我解决了问题! - Daniel D

13

你可以像这样使用age()函数:

SELECT name, EXTRACT(year FROM age(current_date,date_of_birth)) :: int as age FROM public.employees

1
可以仅使用字段而不需要“当前日期”(例如age(date_of_birth))来使用,这种方法非常棒! - Alexander Gorg
你可以使用 age('2021-01-01', date_of_birth) 这个函数来计算年龄。 - Антон Баранов

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接