题解 | #截取出年龄#
截取出年龄
https://www.nowcoder.com/practice/b8d8a87fe1fc415c96f355dc62bdd12f?tpId=199&tqId=1975684&ru=/exam/oj&qru=/ta/sql-quick-study/question-ranking&sourceUrl=%2Fexam%2Foj
select t1.age as age,count(t1.age)as number from (select substring_index(t0.profile,',',1) as age from (select substring_index(profile,',',-2) as profile from user_submit)as t0) as t1 group by age order by t1.age desc
题目中要求截取出年龄,首先想到的便是substring_index函数,但是使用该函数指定逗号‘,’为分隔符之后,无论参数取正还是取负,即不论从前往后截还是从后往前截,都会带出另外一部分数据,因为年龄数据位置是在中间。所以此时应该将第一次截取出来的结果作为一个子查询,在这个查询的基础上,再次使用substring_index函数对子查询结果进行截取,这样便可以实现只将年龄信息截取出来。