SELECT * FROM hr.Employees;
SELECT firstname,
lastname,
(CASE WHEN (month(getdate()) > month(birthdate))
THEN datediff(yy,birthdate,getdate())
ELSE datediff(yy,birthdate,getdate()) -1
END) AS _years, --years
(CASE WHEN (month(getdate()) > month(birthdate))
THEN month(getdate()) - month(birthdate)
ELSE month(getdate()) - month(birthdate) +12
END) AS _months, --months
(CASE WHEN (day(getdate()) > (day(birthdate)))
THEN day(getdate()) - day(birthdate)
ELSE month(getdate()) - month(birthdate) +11 & day(getdate()) + (day(EOMonth(birthdate)) - day(birthdate))
END) AS _days --days
FROM hr.Employees
以下是以yy,mm,dd查找年龄的代码。我遇到的问题是在日期部分。
我想做的是(if current day < birthdate day )
然后(currentMonth-birthmonht)+11 and day(getdate()) + (day(EOMonth(birthdate)) - day(birthdate))
。
答案 0 :(得分:0)
我想做的是(如果是当天&lt; birthdate day)那么 (currentMonth-birthmonht)+11和day(getdate())+ (日(EOMonth(出生日期)) - 日(出生日期))。
这不能在CASE
列的days
中完成,您需要在WHEN
中为CASE
添加新的month
条款列本身。如下面的代码
SELECT firstname,
lastname,
(CASE WHEN (month(getdate()) > month(birthdate)) THEN datediff(yy,birthdate,getdate())
ELSE datediff(yy,birthdate,getdate()) -1
END) AS years,
(CASE WHEN (month(getdate()) > month(birthdate)) THEN month(getdate()) - month(birthdate)
WHEN (day(getdate()) > (day(birthdate))) THEN month(getdate()) - month(birthdate) +11
ELSE month(getdate()) - month(birthdate) +12
END) AS months,
(CASE WHEN (day(getdate()) > (day(birthdate))) THEN day(getdate()) - day(birthdate)
ELSE day(getdate()) + (day(EOMonth(birthdate)) - day(birthdate))
END) AS days
FROM Employees
以下是查询的SQL小提示演示:SQL Fiddle
如果你可以使用T-SQL this答案显示如何在T-SQL中执行此操作。