有人可以帮助一个案例陈述,我需要的是要显示的查询如下。我知道有很多方法可以做到这一点,但我只是需要案例陈述方面的帮助。
- 如果当前月份是“小于”DOB月份,则取“总年”的“1”给我41。 - 如果当前月份是“大于”DOB月,则年龄是正确的。 - 但是如果当前月份与DOB月份“相等”,那么我们需要转到日间级别才能获得正确的年龄。
Set @DOB = '01 November 1971'
Set @Today = GETDATE()
SELECT Datediff(Year,@DOB,@Today) AS Years,
Datepart(Month,@DOB) As DOB_Month,
Datepart(Day, @DOB) as DOB_Day,
DatePart(Month, @Today) As Current_Month,
Datepart(Day,@Today) AS Current_Day
答案 0 :(得分:2)
试试这个:
DECLARE @DOB DATE= '01 November 1971'
DECLARE @TODAY DATE = GETDATE()
SELECT CASE
WHEN DATEPART(MONTH, @TODAY) < DATEPART(MONTH,@DOB) THEN DATEDIFF(YEAR,@DOB,@TODAY) - 1
WHEN DATEPART(MONTH, @TODAY) > DATEPART(MONTH,@DOB) THEN DATEDIFF(YEAR,@DOB,@TODAY)
ELSE
CASE
WHEN DATEPART(DAY, @TODAY) < DATEPART(DAY,@DOB) THEN DATEDIFF(YEAR,@DOB,@TODAY) - 1
ELSE DATEDIFF(YEAR,@DOB,@TODAY)
END
END
答案 1 :(得分:1)
你可以试试这个:
case
when DatePart(Month, @Today) > Datepart(Month,@DOB) then Datediff(Year,@DOB,@Today)
when DatePart(Month, @Today) < Datepart(Month,@DOB) then (Datediff(Year,@DOB,@Today) - 1)
when DatePart(Month, @Today) = Datepart(Month,@DOB) then
case
when DatePart(Day, @Today) >= Datepart(Day,@DOB) then (Datediff(Year,@DOB,@Today) )
when DatePart(Day, @Today) < Datepart(Day,@DOB) then (Datediff(Year,@DOB,@Today) - 1 )
end
end as AgeCompleted,
答案 2 :(得分:0)
declare @DOB date = '19680411'
select datediff(year, @DOB, getdate())- case when month(@DOB)*32 + day(@DOB) >
month(getdate()) * 32 + day(getdate()) then 1 else 0 end