题解 | 截取出年龄
截取出年龄
https://www.nowcoder.com/practice/b8d8a87fe1fc415c96f355dc62bdd12f
# select
# substring_index(substring_index(profile,',',-2),',',1) age,
# count(device_id) number
# from user_submit
# group by age
select substr(profile,locate('kg',profile)+3
,length(substring_index(profile,'kg',-1))-2-length(substring_index(profile,',',-1))) age,
count(device_id) number
from user_submit
group by age
本人刚开始发现使用substring_index(profile,',',-2)之后,看到包括了年龄和年龄和性别,想不通,
看评论后发现可以使用嵌套的方式来获得出我们要的年龄
但是看了一圈,发现说指挥嵌套不行的
就看到了第二种方法,该佬运用多种函数来打到最终年龄的目标,包括locate length substr等函数
首先lodcate函数:第一个参数表示该字母所在 的索引,加3是因为,‘kg’找到的索引为k的索引,加入k的索引为9,往后加3,才能到达年龄第一个数字的索引
后边是算要多长,第一个length求出的结果包括年龄性别还有两个逗号,第二个求出的只有性别,所以第一个length-2得出没有逗号的长度,再减去第二个length中性别的长度就只有年龄的长度了,
这个方法可以防止百岁老人参赛,
再解释下subsrting就是substr第一个参数是表头,第二个参数指的是从哪一个索引开始往后,第三个参数是往后顺延几位
