【问题标题】:PostgreSQL Age Calculation from date type从日期类型计算 PostgreSQL 年龄
【发布时间】:2018-09-20 20:22:57
【问题描述】:

我有下表:

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)
)

如何在输出中列出每个员工的姓名和年龄?

谢谢。

【问题讨论】:

标签: postgresql


【解决方案1】:

使用 date_part() 和 age() 函数

SELECT name text, date_part('year',age(date_of_birth)),* FROM public.employees

有关日期函数的文档,请参阅 https://www.postgresql.org/docs/current/static/functions-datetime.html

【讨论】:

  • 谢谢,只是对 date_part 感到困惑,但你帮我弄清楚了!
【解决方案2】:

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

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

【讨论】:

  • 可以在没有current date 的情况下仅使用字段(例如age(date_of_birth)),无论如何它可以工作,太棒了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多