Non*_*mer 5 sql sql-server date date-difference
有没有一种方法可以根据今天的日期和生日计算某人的年龄,然后以以下方式显示:
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
Run Code Online (Sandbox Code Playgroud)
可能不是最有效的方法,但我是这样做的:
我必须首先获得今天的日期和人的生日之间的日期差异。我用它与 ABS() 和 Remainder (%) 函数结合来获取年、月、日等。
declare @year int = 365
declare @month int = 30
declare @sixYears int = 2190
select
--CAST(DATEDIFF(mm, a.BirthDateTime, getdate()) AS VARCHAR) as GetMonth,
--CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, a.BirthDateTime, getdate()), a.BirthDateTime), getdate()) AS VARCHAR) as GetDays,
CASE
WHEN
DATEDIFF(dd,a.BirthDateTime,getdate()) < @year
THEN
cast((DATEDIFF(dd,a.BirthDateTime,getdate()) / (@month)) as varchar) +' Months & ' +
CAST(ABS(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, a.BirthDateTime, getdate()), a.BirthDateTime), getdate())) AS VARCHAR)
+ ' Days'
WHEN
DATEDIFF(dd,a.BirthDateTime,getdate()) between @year and @sixYears
THEN
cast((DATEDIFF(dd,a.BirthDateTime,getdate()) / (@year)) as varchar) +' Years & ' +
CAST((DATEDIFF(mm, a.BirthDateTime, getdate()) % (12)) AS VARCHAR) + ' Months'
WHEN DATEDIFF(dd,a.BirthDateTime,getdate()) > @sixYears
THEN cast(a.Age as varchar) + ' Years'
end as FinalAGE,
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8493 次 |
| 最近记录: |