Getting age in years in a SQL query

依然范特西╮ 提交于 2019-12-04 21:18:39

Assuming birthday is stored as a DateTime

Select Count(*)
From    (
        Select Id, Floor(DateDiff(d, BirthDate, GetDate()) / 365.25) As Age
        From People
        ) As EmpAges
Where EmpAges Between 20 And 40

This could also be written without the derived table like so:

Select Count(*)
From People
Where Floor(DateDiff(d, BirthDate, GetDate()) / 365.25)  Between 20 And 40

Yet another way would be to use DateAdd. As OMG Ponies and ck mentioned, this one would be the most efficient of the bunch as it would enable the use of an index on dateOfBirth if it existed.

Select Count(*)
From People
Where DateOfBirth Between DateAdd(yy, -40, GetDate()) And DateAdd(yy, -20, GetDate())
select count(*)
from YourTable
where dateofbirth >= '1970-05-24' and dateofbirth <= '1990-05-24'

Adjust the dates according to the current date.

You should compute the dates that form the boundaries of your range, and then use those dates.

DECLARE @Today datetime, @StartDate datetime, @EndDate datetime

SET @Today = DateAdd(dd, DateDiff(dd, 0, GetDate()), 0)
SET @StartDate = DateAdd(dd, 1, DateAdd(yy, -40, @Today))
SET @EndDate = DateAdd(yy, -20, @Today)

SELECT *
FROM People
WHERE DateOfBirth BETWEEN @StartDate AND @EndDate

This gives you a query where you have a chance at using an index.

You could do something like: YEAR(GETDATE()) - YEAR(dateOfBirth) > 20

I'm assuming the people table has birth dates in it.

Rough pseudo code.

Select DateDiff(YY, people.DOB. Datetime.NOW) as age
from people
where age....
JDub

As you always express age as an integer...

select cast(DateDiff(d, people.dob, GetDate()) / 365.25 as int) As Age 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!