首页 > 解决方案 > 来自年份和日期列的年龄 Netezza sql

问题描述

我有像 ID 这样的数据元素;开始日期; 出生年。我想根据 AGE 列中所示的birth_year 列和 start_date 计算 Age。

在此处输入图像描述

我只能想到用'-01-01'填充出生年份,然后使用该列计算年龄。

在 Netezza SQL 中是否有另一种从出生年份和开始日期获取年龄的有效方法?

标签: sqlnetezza

解决方案


使用extract SQL 函数从 start_date 获取年份并计算年龄

例如


select
    start_date,
    birth_year,
    -- assuming birth_year is an integer
    extract(year from start_date) - birth_year as age
from ... 

会给

 START_DATE | BIRTH_YEAR | AGE
------------+------------+-----
 2000-01-15 |       1985 |  15
 2010-06-20 |       1990 |  20
 2005-12-15 |       1992 |  13
 2007-08-17 |       1998 |   9
 2020-09-15 |       1999 |  21
(5 rows)

获取更详细年龄的另一种方法是使用Netezza 'age' SQL 函数-

select
    start_date,
    birth_year,
    age(start_date, to_date(birth_year, 'YYYY'))
from...

这将导致

 START_DATE | BIRTH_YEAR |           AGE
------------+------------+--------------------------
 2000-01-15 |       1985 | 15 years 14 days
 2010-06-20 |       1990 | 20 years 5 mons 19 days
 2005-12-15 |       1992 | 13 years 11 mons 14 days
 2007-08-17 |       1998 | 9 years 7 mons 16 days
 2020-09-15 |       1999 | 21 years 8 mons 14 days
(5 rows)

推荐阅读