简体   繁体   English

如何计算两个日期之间的确切年数

[英]How to calculate exact number of years between two dates

I have two columns, Birth_Date and Publish_Date.我有两列,Birth_Date 和 Publish_Date。 I need to calculate number of years (taking into account months) between the Publish_Date and Birth_Date.我需要计算 Publish_Date 和 Birth_Date 之间的年数(考虑月份)。 (DATE, FORMAT'YYYYMMDD') (日期,格式'YYYYMMDD')

I have attempted to use DATEDIFF, however it does not seem to be picking this up.我曾尝试使用 DATEDIFF,但它似乎并没有解决这个问题。 Solution from here: How to calculate age (in years) based on Date of Birth and getDate()此处的解决方案: 如何根据出生日期和 getDate() 计算年龄(以年为单位)

,  CASE WHEN dateadd(year, datediff (year, Brth_Dt, Pub_Dt), Brth_Dt) > Pub_Dt
        THEN datediff(year, Brth_Dt, Pub_Dt) - 1
        ELSE datediff(year, Brth_Dt, Pub_Dt)
   END as Brth_Yrs

Error: SELECT Failed.错误:SELECT 失败。 3706: Syntax error: expected something between '(' and the 'year' keyword. 3706: 语法错误:期望在 '(' 和 'year' 关键字之间有一些东西。

Also tried this solution from How to calculate Age/Number of Years between two dates还从如何计算两个日期之间的年龄/年数中尝试了这个解决方案


  ,    DATEDIFF(YEAR, Brth_Dt, Pub_dt) + 
                         CASE 
                           WHEN MONTH(@Pub_dt) < MONTH(Brth_Dt) THEN -1 
                           WHEN MONTH(@Pub_dt) > MONTH(Brth_Dt) THEN 0 
                           ELSE 
                             CASE WHEN DAY(@Pub_dt) < DAY(Brth_Dt) THEN -1 ELSE 0 END 
                         END)    As Brth_Yrs

Error: SELECT Failed.错误:SELECT 失败。 3706: Syntax error: expected something between '(' and the 'YEAR' keyword. 3706: 语法错误:期望在 '(' 和 'YEAR' 关键字之间有一些东西。

Can anyone help on how to write this?谁能帮忙写这个?

Try the below SQL QUERY for finding Year difference between two dates using DATEDIFF function.尝试下面的 SQL QUERY 查询,使用 DATEDIFF function 查找两个日期之间的年份差异。

SELECT DATEDIFF(year, Brth_Dt, Pub_Dt) AS date_difference FROM Employee; SELECT DATEDIFF(year, Brth_Dt, Pub_Dt) AS date_difference FROM Employee;

Teradata does not support DATEDIFF, DATEADD functions. Teradata 不支持 DATEDIFF、DATEADD 函数。

Here is one way of calculating age to current date.这是计算当前日期年龄的一种方法。 We turn the dates into integers in YYYYMMDD format using Teradata's EXTRACT function to extract date parts;我们使用 Teradata 的 EXTRACT function 将日期转换为 YYYYMMDD 格式的整数以提取日期部分; we then simply subtract DOB from the current date.然后我们简单地从当前日期中减去 DOB。

You can just substitute CURRENT_DATE with your Publish_Date and DOB with Birth_Date.您可以将 CURRENT_DATE 替换为 Publish_Date,将 DOB 替换为 Birth_Date。

 ((EXTRACT(YEAR FROM CURRENT_DATE)*10000+
   EXTRACT(MONTH FROM CURRENT_DATE)*100+
   EXTRACT(DAY FROM CURRENT_DATE)) -
  (EXTRACT(YEAR FROM DOB)*10000+
   EXTRACT(MONTH FROM DOB)*100+
   EXTRACT(DAY FROM DOB))
 )/10000 as Age

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

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