我有一个访问过的表格如下:
Name:-----Birthdate:-----Section----etc...
John------10/10/1985-----etc...
Mike------02/03/1976-----etc...
还有更多。
如何进行获取表中人员年龄,计算并显示范围的SQL查询?
类似的东西:
Group1 ( From 18 to 25 ): 2 people
Group2 ( From 26 to 35 ): 1 person
...
感谢您的回答!
答案 0 :(得分:1)
您可以使用datediff
来计算某人的年龄:
datediff('yyyy', Birthdate, now())
switch
应允许您对范围进行分组:
select AgeGroup
, count(*)
from (
select switch(
datediff('yyyy', Birthdate, now()) between 18 and 25, '18 to 25',
datediff('yyyy', Birthdate, now()) between 26 and 35, '26 to 35',
true, 'other') as AgeGroup
from YourTable
) as SubQueriesMustBeNamed
group by
AgeGroup
答案 1 :(得分:0)
它可能会帮助你
select d,cast(count(d) as nvarchar(max)) + ' persons' as total from
(
select case
when CONVERT(int,ROUND(DATEDIFF(hour,Birthdate,GETDATE())/8766.0,0)) between 10 and 20 then '10-20'
else '>20' end as d from YourTable
) a
group by d