标题解释了我的整个问题。这是查询:
select
date_format(now(), '%Y') - date_format(date_of_birth, '%Y') age,
IF(date_format(now(), '%Y') - date_format(date_of_birth, '%Y') < 18,
'Under 18',
IF(date_format(now(), '%Y') - date_format(date_of_birth, '%Y') <= 24,
'19 to 24',
IF(date_format(now(), '%Y') - date_format(date_of_birth, '%Y') <= 34,
'25 to 34',
'Over 34'))) age_range
from customer
答案 0 :(得分:0)
看起来很适合CASE
。
应该看起来像以下(未经测试):
select
date_format(now(), '%Y') - date_format(date_of_birth, '%Y') age,
CASE age
WHEN age < 18 THEN 'Under 18'
WHEN age <= 24 THEN '19 - 24'
WHEN age <= 34 THEN '25 - 34'
ELSE 'Over 34'
END CASE AS age_range
from customer
答案 1 :(得分:0)
我建议使用case和嵌套查询的组合 - 类似于:
select s.age,
case when s.age < 18 then 'Under 18'
when s.age <= 24 then '19 to 24'
when s.age <= 34 then '25 to 34'
else 'Over 34'
end case as age_range
from (select date_format(now(), '%Y') - date_format(date_of_birth, '%Y') as age
from customer) s