Bigquery中年龄的计算

Calculation of age in Bigquery

任何人都可以帮助我在 Bigquery 中找到年龄函数的替代方法。 下面是 netezza 数据库中 AGE 函数的一些示例。 例如:

SELECT AGE(Current_date,'1994-07-16');

o/p: 27 岁 2 周一 21 天

提前致谢。

试试这个自定义函数。此函数不处理闰年。

create function mydataset.age(_date date)
returns string  
as
(
    (
        select  concat(
            case when years = 0 then '' else  concat(cast(years as string),' Year ') end,
            case when months = 0 then '' else  concat(cast(months as string),' Month') end,
            case when days = 0 then '' else  cast(days as string) end,' Day'
            )
    from (
        select
        div(date_diff(current_date(),_date,day),365) years,
        div(mod(date_diff(current_date(),_date,day),365),30) months,
        mod(mod(date_diff(current_date(),_date,day),365),30) days
    )
    )
        
)

考虑以下方法

create temp function age (dob date, base date) as ((
  select format('%i years %i months %i days', years, months, date_diff(base, temp_date2, day))
  from (
    select *,
      date_diff(base, temp_date, month) - day_check months,
      date_add(temp_date, interval date_diff(base, temp_date, month) - day_check month) temp_date2   
    from (
      select *,
        date_diff(base, dob, year) - month_check as years,
        date_add(dob, interval date_diff(base, dob, year) - month_check year) temp_date
      from (
        select 
          if(extract(month from base) < extract(month from dob), 1, 0) month_check,
          if(extract(day from base) < extract(day from dob), 1, 0) day_check
      )
    )
  )    
));
select age('1994-07-16', current_date) as age    

有输出