练习网站为牛客网
1. SQL25 查找山东大学或者性别为男生的信息
题目:现在运营想要分别查看学校为山东大学或者性别为男性的用户的device_id、gender、age和gpa数据,请取出相应结果,结果不去重。
注意点:分别查看&结果不去重:所以直接使用两个条件的or是不行的,直接用union也不行,要用union all,分别去查满足条件1的和满足条件2的,然后合在一起不去重
select device_id, gender, age, gpa
from user_profile
where university = '山东大学'
union all
select device_id, gender, age, gpa
from user_profile
where gender = 'male'
2. SQL26 计算25岁以上和以下的用户数量
题目:现在运营想要将用户划分为25岁以下和25岁及以上两个年龄段,分别查看这两个年龄段用户数量
题解:使用CASE函数。
select case
when age < 25 or age IS NULL then '25岁以下'
when age >= 25 then '25岁及以上'
end age_cut, count(*) as number
from user_profile
group by age_cut
3.SQL27 查看不同年龄段的用户明细
题目:现在运营想要将用户划分为20岁以下,20-24岁,25岁及以上三个年龄段,分别查看不同年龄段用户的明细情况,请取出相应数据。(注:若年龄为空请返回其他。)
select device_id, gender, CASE
when age < 20 then '20岁以下'
when age >= 20 and age < 25 then '20-24岁'
when age >=25 then '25岁及以上'
ELSE '其他'
END AS age_cut
from user_profile;
4.SQL28 计算用户8月每天的练题数量
题目:现在运营想要计算出2021年8月每天用户练习题目的数量,请取出相应数据。
注意点:取出日期的年、月、日的方法
month(date), year(date), day(date)
select day(date), count(question_id) as question_cnt
from question_practice_detail
where date between '2021-08-01' and '2021-08-31'
#where month(date) = 8 and year(date) = 2021
group by date
5. SQL30 统计每种性别的人数
题目:现在运营举办了一场比赛,收到了一些参赛申请,表数据记录形式如下所示,现在运营想要统计每个性别的用户分别有多少参赛者,请取出相应结果。
device_id profile blog_url
2138 180cm,75kg,27,male http:/url/bigboy777
注意:从profile里面取出性别
substring_index
比如 substring_index(profile, ',', -1)
substring_index
最后一个参数,1,表示取第一个,2表示取1-2, 3 表示取1-3
如果需要取某个值,用两次 substring_index
。