用SQL计算一个人的年龄 [英] Calculate age of a person in SQL
本文介绍了用SQL计算一个人的年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
如何在T-SQL中计算年龄年,月,日
看似简单,但对我来说似乎不起作用.我想根据SQL中的两个日期来计算某人的年龄.
It seems like something simple, but it doesn't seem to work for me. I want to calculate the age of someone base on two dates in SQL.
我做了DATEDIFF(year,Birthdate,ReferenceDate),但它并不总是能给我合适的年龄.
I did DATEDIFF(year,Birthdate,ReferenceDate) and it doesn't always give me the right age.
例如
DATEDIFF(year,'1981-07-05',2011-07-01')
给出30,但仍然应该为29.有没有办法做到这一点?
gives 30, while it should still be 29. Is there a way to do this ?
谢谢
推荐答案
尝试一下...
SELECT CASE WHEN
(DATEADD(year,DATEDIFF(year, @datestart ,@dateend) , @datestart) > @dateend)
THEN DATEDIFF(year, @datestart ,@dateend) -1
ELSE DATEDIFF(year, @datestart ,@dateend)
END
它只是比较年份差异,如果相差较大,则减去年份,否则返回该值.
It just compares the year difference and if it is greater then subtracts a year, else it returns the value.
这篇关于用SQL计算一个人的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文