我有一个sql表,用于存储人员的详细信息,例如id,name,DoB,registration_date和address。我想计算每个人的年龄,然后将他们分成这些范围:20-30,31-50,51&结束了。
我知道我可以这样做:(https://stackoverflow.com/a/1572257/3045800)
SELECT FLOOR((CAST (GetDate() AS INTEGER) - CAST(Date_of_birth AS INTEGER)) / 365.25) AS Age
我只需要弄清楚如何将所有人分组到各自的范围内。
感谢您的帮助
答案 0 :(得分:6)
使用case
生成年龄组说明:
select *,
case
when datediff(now(), date_of_birth) / 365.25 > 50 then '51 & over'
when datediff(now(), date_of_birth) / 365.25 > 30 then '31 - 50'
when datediff(now(), date_of_birth) / 365.25 > 19 then '20 - 30'
else 'under 20'
end as age_group
from person
请注意计算年龄的简单方法。
答案 1 :(得分:2)
您可以将 与 构建:
一起使用with Query as (
select FLOOR((CAST (GetDate() AS INTEGER) - CAST(Date_of_birth AS INTEGER)) / 365.25) AS Age
... -- Other fields
from MyTable
)
select case
-- whatever ranges you want
when (Age < 20) then
1
when (Age >= 20) and (Age <= 30) then
2
when (Age > 30) and (Age <= 50) then
3
else
4
end AgeRange,
...
from Query
group by AgeRange
答案 2 :(得分:0)
我曾经面对同样的要求,这就是我如何解决它:我希望有一种直接的方式,因为这不是:
SELECT (CASE
WHEN G.DATE_OF_BIRTH IS NULL
THEN
'18-24' --Put your default Range In case the date of birth is null
ELSE
CASE
WHEN EXTRACT (
YEAR FROM (select sysdate from dual))
- EXTRACT (YEAR FROM g.DATE_OF_BIRTH) < 18
THEN
'MINORS'
ELSE
CASE
WHEN EXTRACT (
YEAR FROM (select sysdate from dual))
- EXTRACT (YEAR FROM g.DATE_OF_BIRTH) BETWEEN 25
AND 29
THEN
'25-29'
ELSE
CASE
WHEN EXTRACT (
YEAR FROM (select sysdate from dual))
- EXTRACT (YEAR FROM g.DATE_OF_BIRTH) BETWEEN 30
AND 34
THEN
'30-34'
ELSE
CASE
WHEN EXTRACT (
YEAR FROM (select sysdate from dual))
- EXTRACT (
YEAR FROM g.DATE_OF_BIRTH) BETWEEN 35
AND 39
THEN
'35-39'
ELSE
CASE
WHEN EXTRACT (
YEAR FROM (select sysdate from dual))
- EXTRACT (
YEAR FROM g.DATE_OF_BIRTH) BETWEEN 40
AND 49
THEN
'40-49'
ELSE
CASE
WHEN EXTRACT (
YEAR FROM (select sysdate from dual))
- EXTRACT (
YEAR FROM g.DATE_OF_BIRTH) BETWEEN 50
AND 59
THEN
'50-59'
ELSE
CASE
WHEN EXTRACT (
YEAR FROM (select sysdate from dual))
- EXTRACT (
YEAR FROM g.DATE_OF_BIRTH) BETWEEN 60
AND 69
THEN
'60-69'
ELSE
CASE
WHEN EXTRACT (
YEAR FROM (select sysdate from dual))
- EXTRACT (
YEAR FROM g.DATE_OF_BIRTH) >=
70
THEN
'ELDERLY'
END
END
END
END
END
END
END
END
END) from your table g
这只是一个例子。用您的首选项替换范围。我已经使用了Oracle。