请问一个案例说明可以帮助一下,我需要的查询显示如下。我知道有一些方法可以使此操作更容易,但是我只需要在案例声明中提供帮助。
-如果当前月是“大于” 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
试试这个 :
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