0

有人可以帮忙做一个案例陈述吗,我需要的是要显示的查询如下。我知道有一些方法可以更轻松地做到这一点,但我只需要案例陈述方面的帮助。

--如果当前月份“小于”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
4

3 回答 3

3

试试这个 :

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
于 2013-03-04T09:21:48.547 回答
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,
于 2013-03-04T09:12:54.173 回答
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
于 2013-03-04T13:51:20.857 回答