Hello I've been tasked with doing a few queries on a large SQL Server 2000 database.
The query I'm having trouble with is "find the number of people between ages 20 and 40"
How would I do this? My previous query to get a count of everyone looks like this:
select count(rid) from people where ...
(with the ... being irrelevant conditions). I've googled some but the only thing I've found for calculating age is so large that I don't see how to embed it into a query, or it is a stored procedure which I do not have the permissions to create.
Can someone help me with this?
The relevant part of the people table is like so:
RID(unique key) | dateofbirth(datetime) | firstname....
I'm assuming the people table has birth dates in it.
Rough pseudo code.
Assuming birthday is stored as a DateTime
This could also be written without the derived table like so:
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.
As you always express age as an integer...
You could do something like: YEAR(GETDATE()) - YEAR(dateOfBirth) > 20
You should compute the dates that form the boundaries of your range, and then use those dates.
This gives you a query where you have a chance at using an index.
Adjust the dates according to the current date.