Mysql学习笔记(七)

  • 去重函数distinct
    删除重复项取唯一值
    案例一
--针对table1 中的id,name去重,取唯一值
select distinct id
	,name
from table1
;

案例二

--针对table1中的id去重后统计数量
select count(distinct id) as id_cnt
from table1
;

案例三

--针对table1中的id,name去重后统计数量(即id和name均相同的统计为1)
select count(distinct id,name) as cnt
from table1
;
  • 字符串分割函数SUBSTRING_INDEX
    用于从字符串中获取指定分隔符分割后的子串
    语法:SUBSTRING_INDEX(str,delim,count),其中,str 是要分割的字符串,delim 是分隔符,count 表示返回的子串数量
    案例一
    在这里插入图片描述
    解析:
--substring_index(profile, ',', 3) 返回3个字串
select substring_index(profile, ',', -1) as gender
	,count(device_id) as number
from user_submit
group by gender
;

其他解题思路:
1.使用 case when + like 拆分出性别作为gender字段后统计

select 
	--case when 有顺序,female中包含字符male,先选出female防止将female误分为male
	case 
		when profile like '%female%' then  'female'
		when profile like '%male%' then 'male'
		else '其他'
	end as gender
	,count(device_id) as number
from user_submit
group by gender
;
--或者
select 
	--加上‘,’作为识别
	case
		when profile like '%,male' then 'male'
		when profile like '%,female' then 'female'
		else '其他'
	end as gender
from user_submit
group by gender
;
	 

2.使用 case when + find_in_set
find_in_set(str, strlist) 其中 str 为要查询的字符串,strlist 为被查询的字段,精确匹配,以英文 ‘,’ 分隔;

select 
	case
		when find_in_set('female', profile) then 'female'
		when find_in_set('male',profile) then 'male'
		else '其他'
	end as gender
	,count(device_id) as number
from user_submit
group by gender
;

案例二
在这里插入图片描述
解析:

--截取出年龄,再根据年龄分组计数
select substring_index(substring_index(profile,',',3),',',-1) as age
	,count(device_id) as number
from user_submit
group by age
;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值