postgresql 如何在postgresql选择查询中仅从age()函数中获取年份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40484345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:26:18  来源:igfitidea点击:

How to get only year from age() function in postgresql select query

sqlpostgresql

提问by Vikrant

The following query returns:

以下查询返回:

SELECT AGE(cast(dob AS date)) 
FROM mas_patient_details;

age
----------
39 years 5 mons 19 days
13 years 2 days
69 years 2 days
41 years 11 mons 25 days

This query returns:

此查询返回:

SELECT age(cast(dob as date)) 
FROM mas_patient_details 
WHERE age <= 59;

age
----------
39 years 5 mons 19 days
13 years 2 days
69 years 2 days
41 years 11 mons 25 

How would one extract simply the year from one of these queries?

如何从这些查询之一中简单地提取年份?

回答by Vikrant

If column fu is of data type DATE, you could use

如果列 fu 的数据类型为 DATE,则可以使用

SELECT EXTRACT(YEAR FROM fu) FROM mydate;

and if it is varchar, you convert it to date using to_date()

如果是 varchar,则使用 to_date() 将其转换为日期

SELECT EXTRACT(YEAR FROM to_date(fu, <your pattern>)) FROM mydate;

In your case:

在你的情况下:

select EXTRACT(YEAR FROM age(cast(dob as date))) 
from mas_patient_details 
where age <= 59;