题目详情
题目:现在运营举办了一场比赛,收到了一些参赛申请,表数据记录形式如下所示,现在运营想要统计每个性别的用户分别有多少参赛者,请取出相应结果
示例:user_submit
根据示例,你的查询应返回以下结果:
gender number male 2 female 3
解题
-
暴力解决【case when】
1️⃣结果表中需要gender
和number
。表头需要as
来统一命名;
2️⃣性别分类profile
中属于字符串,我们可以使用模糊查找like
的方式对male
和female
进行字段值“变更”。
⭕️这里注意一定加上前面的逗号,
,不加逗号的话将会全部分为male
,因为所有female
前面两个字母fe
也会被%
给取代。
一定使用group by gender
进行性别分类。
执行顺序是先group by
→ \rightarrow →where
→ \rightarrow →select
【即select一定是在分组之后进行】
3️⃣ 计数count(device_id)
select case when profile like '%,male' then 'male' when profile like '%,female' then 'female' end as gender, count(device_id) from user_submit group by gender;
-
字符串截取函数
substring_index
substring_index(str,delim,count) //str:截取字符串 //delim:分隔符[, . / _ ] //count:计数【正数正着数,负数倒着数】
可以理解成Python里的
split
函数,拆分后会被分为好几个部分放在一个列表里。SELECT SUBSTRING_INDEX(profile,",",-1) gender,COUNT(*) number FROM user_submit GROUP BY gender;
题目详情
编写 SQL 语句,返回顾客 ID(cust_id)、顾客名称(cust_name)和登录名(user_login),其中登录名全部为大写字母,并由顾客联系人的前两个字符(cust_contact)和其所在城市的前三个字符(cust_city)组成。提示:需要使用函数、拼接和别名。
解题
-
substring(str, start, length)
substring(str,start,length) //str:截取字符串 //start:起始位置 //length:截取子串长度
从任意位置开始截取子串
-
left(str,length)
left(str,length) //str:截取字符串 //length:左起数,子串长度
从左边开始截取子串
-
concat(str1,str2)
类似于Python的字符串拼接方法,不多加赘述。