Case Statement with Datediff and DatePart

2019-06-12 16:20发布

问题:

Can some one help with a case statement please, what I need is the query to show is the following. I know there are ways to do this easier but I just need help on the Case Statement.

--If the Current Month is ‘Less Than’ the DOB Month, then take ‘1’ of the Total Years to give me 41. --If the Current Month is ‘Greater Than’ the DOB Month then the Age is Correct. --However if the Current Month is ‘Equal’ to the DOB Month then we need to go to Day level to get the correct Age.

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

回答1:

Try this :

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


回答2:


You can try this :

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,


回答3:

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


标签: sql tsql