题解 | #查看不同年龄段的用户明细#
查看不同年龄段的用户明细
http://www.nowcoder.com/practice/ae44b2b78525417b8b2fc2075b557592
解法一
select device_id, gender,
(case
when age<20 then '20岁以下'
when age>=20 and age<25 then '20-24岁'
when age>=25 then '25岁及以上'
else '其他'
end) as age_cut
from user_profile;
解法二
select device_id, gender,
if(age<20,'20岁以下',
if(age>=20 and age<25,'20-24岁',
if(age>=25,'25岁及以上','其他'))) as age_cut
from user_profile;
目前位置第一次使用if函数,虽然一直在想sql应该是有IF函数的。
在两个解法运行过程中可以发现,在这种情况下解法二是优于解法一的。
好好学习这两个函数吧。
MySQL试题答案解析 文章被收录于专栏
MySQL在线编程重点试题解析