简体   繁体   English

使用 date_diff 计算日期列与 current_date 之间的差异,以年/月/日显示

[英]Using date_diff to calculate diffence between a date column and current_date, displayed in years/months/days

I'm currently trying to create a column for how old an account is in Athena, I have the date column the account was created and want the column to display the account_age as years/months/days我目前正在尝试为 Athena 中的帐户年龄创建一个列,我有创建帐户的日期列,并希望该列将 account_age 显示为年/月/天

    CAST(DATE_DIFF('year', cu.reg_date, current_date) as varchar)||' years '||
 CAST(DATE_DIFF('month', cu.reg_date, current_date) AS VARCHAR)||' months '||
 CAST(DATE_DIFF('day', cu.reg_date, current_date) -
               (COALESCE(DATE_DIFF('month', cu.reg_date, CURRENT_DATE), 1) * 30)
              AS VARCHAR)||' days'as account_age

the code above brings back years then total months and the days is off.上面的代码带回数年,然后是总月数,天数是关闭的。 The years seems ok but I don't want total months, just the months when full years have been taken away.这些年似乎还可以,但我不想要总月数,只想要整年都被带走的月份。

Months are easy, just use the remainder of the division by 12:几个月很简单,只需使用除以 12 的余数:

CAST(DATE_DIFF('month', cu.reg_date, current_date) % 12 AS VARCHAR)||' months '

Days will be harder - you can try adding total passed months to the starting date and then calculate the diff in days:日子会更难 - 您可以尝试将过去的总月数添加到开始日期,然后以天为单位计算差异:

CAST(date_diff('day', date_add('month', date_diff('month', cu.reg_date, current_date), cu.reg_date), current_date) AS VARCHAR)||' days' 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM