可能重复:
How to calculate age in T-SQL with years, months, and days
在我正在进行的项目中,我被要求计算他们加入系统时的年龄;在互联网上查找之后,我发现了各种方法可以做到这一点,但是当涉及到闰年时,大多数都有轻微的问题。
以下解决方案是我如何计算过去/年龄的年数。希望这有助于其他人
答案 0 :(得分:14)
您需要将以下方法添加到数据库中:
CREATE FUNCTION [dbo].[fnCalAge] (@DiffFrom DATE, @DiffTo DATE) RETURNS INT
AS
BEGIN
DECLARE @NumOfYears INT
SET @NumOfYears = (SELECT
DATEDIFF(YEAR, @DiffFrom, @DiffTo) +
CASE
WHEN MONTH(@DiffTo) < MONTH(@DiffFrom) THEN -1
WHEN MONTH(@DiffTo) > MONTH(@DiffFrom) THEN 0
ELSE
CASE WHEN DAY(@DiffTo) < DAY(@DiffFrom) THEN -1 ELSE 0 END
END)
IF @NumOfYears < 0
BEGIN
SET @NumOfYears = 0;
END
RETURN @NumOfYears;
END
然后在SQL查询中调用它,类似于以下内容:
SET DATEFORMAT dmy
SELECT dbo.fnCalAge(CAST('20/06/1987' AS DATE), CAST('20/06/2013' AS DATE))
答案 1 :(得分:7)
假设@bDate是生日的日期时间,@今天是今天的日期,那么......
Declare @bDay Date = '31 dec 2000'
Declare @today Date = cast(getdate() as date)
Select datediff(Year, @bDay, @today) -
case When datepart(dayofYear, @today) <
datepart(dayofYear, @bDay) Then 1 Else 0 End
答案 2 :(得分:1)
将Dired替换为DOB以适应年龄。将sysdate替换为您的日期,例如to_date('28 -DEC-2012'):
SELECT empno, ename, hiredate, TRUNC(MONTHS_BETWEEN(sysdate, hiredate)/12) years_of_service
FROM scott.emp
/