簡體   English   中英

從過去的特定日期使用 DoB 計算年齡

[英]Calculating Age Using DoB from a Specific Date in the past

我正在尋求一些幫助:

我需要計算截至 2020 年 2 月 1 日的成員年齡(DoB 字段)。 例如,如果成員的 DoB 為 2/18/91,我希望看到兩個字段。 1 為會員截至今天的實際年齡,然后是會員截至 2020 年 2 月 1 日的年齡。 在此示例中,第一個字段中的年齡應為 30,但第二個字段中應為 29。

我嘗試使用一些 datefiff 和 datepart,但我似乎無法得到它。 我正在使用 SSMS 2016。

你的計算是錯誤的。 那個人當時應該是28歲。

一個簡單的技巧是將日期視為 yyyyMMdd 形式的數字,然后從 DOB 中減去目標日期,得到 integer 部分。 使用您的示例日期:

DECLARE @dob DATETIME='19910218';
DECLARE @targets TABLE(target DATETIME);
INSERT @targets(target)VALUES('20200201'), (GETDATE());
SELECT
     FLOOR(((YEAR(target)* 10000+MONTH(target)* 100+DAY(target))
            -(YEAR(@dob)* 10000+MONTH(@dob)* 100+DAY(@dob))
           )/ 10000
          )
FROM @targets;

PS:地板可能是不必要的,SQL 服務器進行了 integer 划分,但我想保持安全。

將日期轉換為 8 個字符的整數,減去並除以 10000:

declare @Birthdate date = '2/18/91'
declare @AsOfDate  date = '2/1/2020'
select (0+convert(char(8),getdate(),112) - convert(char(8),@birthdate,112)) / 10000 as CurrentAge
     , (0+convert(char(8),@asofdate,112) - convert(char(8),@birthdate,112)) / 10000 as FebAge
datediff(year, <birthdate>, <currentdate>) +
case when
      month(<birthdate>) > month(<currentdate>) or
      month(<birthdate>) = month(<currentdate>) and
      day(<birthdate>) > day(<currentdate>)
    then -1 else 0 end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM