在SQL查询中获取年龄 [英] Getting age in years in a SQL query
问题描述
我遇到的问题是找到20到40岁之间的人数
我该怎么做?我以前的查询得到每个人的数量如下所示:
从其中选择count(rid)...
(与...无关的条件)。我已经搜索了一些,但我发现计算年龄的唯一的事情是如此之大,以至于我没有看到如何将其嵌入到查询中,或者是一个我没有创建权限的存储过程。
有人可以帮我吗?
People表的相关部分如下:
RID(唯一键)| dateofbirth(datetime)| firstname ....
假设生日存储为日期时间
选择计数(*)
从(
选择ID,Floor(DateDiff(d,BirthDate ,GetDate())/ 365.25)作为年龄
从人民币
)作为EmpAges
其中EmpAges在20和40
这也可以写成没有派生表如下:
选择计数(*)
从人民币
其中Floor(DateDiff(d,BirthDate,GetDate())/ 365.25)20和40
另一种方法是使用DateAdd。正如OMG Ponies和ck所提到的,这将是最有效率的,因为它可以使用dateOfBirth上的索引(如果存在)。
$($)
从人民币
其中DateOfBirth之间DateAdd(yy,-40,GetDate())和DateAdd(yy,-20,GetDate())
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....
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())
这篇关于在SQL查询中获取年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!