知识点:
(1)substring_indexsubstring_index(str,delim,count)
str:要处理的字符串
delim:分隔符
count:计数
(2)切割、截取、删除、替换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | select -- 替换法 replace(string, '被替换部分','替换后的结果') -- device_id, replace(blog_url,'http:/url/','') as user_name -- 截取法 substr(string, start_point, length*可选参数*) -- device_id, substr(blog_url,11,length(blog_url)-10) as user_nam -- 删除法 trim('被删除字段' from 列名) -- device_id, trim('http:/url/' from blog_url) as user_name -- 字段切割法 substring_index(string, '切割标志', 位置数(负号:从后面开始)) device_id, substring_index(blog_url,'/',-1) as user_name from user_submit; |
30、现在运营举办了一场比赛,收到了一些参赛申请,表数据记录形式如下所示,现在运营想要统计每个性别的用户分别有多少参赛者,请取出相应结果
示例:user_submit
device_id | profile | blog_url |
2138 | 180cm,75kg,27,male | http:/url/bigboy777 |
3214 | 165cm,45kg,26,female | http:/url/kittycc |
6543 | 178cm,65kg,25,male | http:/url/tiger |
4321 | 171cm,55kg,23,female | http:/url/uhksd |
2131 | 168cm,45kg,22,female | http:/urlsydney |
方法1:
select SUBSTRING_INDEX(profile,",",-1) gender,
count(device_id) as number
from user_submit
group by gender
方法2:
SELECT IF(profile LIKE '%female','female','male') gender,COUNT(*) number
FROM user_submit
GROUP BY gender;
方法3:
SELECT
case when profile like '%,female' then 'female'
when profile like '%,male' then 'male'
else '其他'
end as gender,
COUNT(*) number
FROM user_submit
GROUP BY gender;
根据示例,你的查询应返回以下结果:
gender | number |
male | 2 |
female | 3 |
31、对于申请参与比赛的用户,blog_url字段中url字符后的字符串为用户个人博客的用户名,现在运营想要把用户的个人博客用户字段提取出单独记录为一个新的字段,请取出所需数据。
方法1:
select device_id,
SUBSTRING_INDEX(blog_url,"/",-1) user_name
from user_submit
方法2:
-- 替换法 replace(string, '被替换部分','替换后的结果')
select
device_id, replace(blog_url,'http:/url/','') as user_name
from user_submit;
方法3:
-- 截取法 substr(string, start_point, length*可选参数*)
select
device_id, substr(blog_url,11,length(blog_url)-10) as user_name
from user_submit;
方法4:
-- 删除法 trim('被删除字段' from 列名)
select
device_id, trim('http:/url/' from blog_url) as user_name
from user_submit;
方法5:
-- 字段切割法 substring_index(string, '切割标志', 位置数(负号:从后面开始))
select
device_id, substring_index(blog_url,'/',-1) as user_name
from user_submit;
返回以下结果:
device_id | user_name |
2138 | bisdgboy777 |
3214 | dkittycc |
6543 | tigaer |
4321 | uhsksd |
2131 | sydney |
32、现在运营想要统计每个年龄的用户分别有多少参赛者,请取出相应结果
--substring_index()函数返回的是截取到多少位,不是截取第几位
select substring_index(profile, ',', -2) as age,
count(device_id) as number
from user_submit
group by age
返回结果:
27,male | 1 |
26,female | 1 |
25,male | 1 |
23,female | 1 |
22,female | 1 |
select substring_index(substring_index(profile, ',', -2),',', 1) as age,
count(device_id) as number
from user_submit
group by age
返回以下结果:
age | number |
27 | 1 |
26 | 1 |
25 | 1 |
23 | 1 |
22 | 1 |