获取年,月和日SQL的日期差异

有没有办法根据今天的日期和他们的生日来计算某人的年龄,然后以下列方式显示:

If a user is less than (<) 1 year old THEN show their age in MM & days.
Example:  10 months & 2 days old 

If a user is more than 1 year old AND less than 6 years old THEN show their age in YY & MM & days.
Example:  5 years & 3 months & 10 days old

If a user is more than 6 years old THEN display their age in YY.
Example:  12 years

最佳答案 这基本上就是你要找的东西:

DECLARE @date1 DATETIME
     , @date2 DATETIME;

SELECT @date1 = '1/1/2008'
    , @date2 = GETDATE();
SELECT CASE
         WHEN DATEDIFF(YEAR, @date1, @date2) < 1 THEN CAST(DATEDIFF(mm, @date1, @date2) AS VARCHAR)+' Months & '+CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, @date1, @date2), @date1), @date2) AS VARCHAR)+' Days'
         WHEN DATEDIFF(YEAR, @date1, @date2) BETWEEN 1 AND 5 THEN CAST(DATEDIFF(mm, @date1, @date2) / 12 AS VARCHAR)+' Years & '+CAST(DATEDIFF(mm, @date1, @date2) % 12 AS VARCHAR)+' Months'
         WHEN DATEDIFF(YEAR, @date1, @date2) >= 6 THEN CAST(DATEDIFF(YEAR, @date1, @date2) AS VARCHAR)+' Years'
      END;

当用户小于(<)1岁时的结果然后显示他们的年龄在MM&天: 《获取年,月和日SQL的日期差异》

当用户超过1岁且小于6岁时的结果然后显示他们的年龄在YY& MM&天:

《获取年,月和日SQL的日期差异》

当用户超过6岁时的结果然后在YY中显示他们的年龄:

《获取年,月和日SQL的日期差异》

点赞