Mysql牛客网刷题记录

1.限制返回行数

查询结果限制返回行数_牛客题霸_牛客网

例如返回前两行

  • select device_id from user_profile limit 0,2---运行效率更高
  • select device_id from user_profile limit 2 ---运行效率低
  • 结合 limit offset: 一起使用时,limit表示要取的数量,offset表示跳过的数量
    • select device_id from user_profile limit 2 offset 0 // 跳过0条,从第一条数据开始取,取两条数据 ---运行效率中

检索记录行 6-10

   SELECT * FROM table LIMIT 5,5

检索记录行 11-last

   SELECT * FROM table LIMIT 10,-1

2.将年龄划分为25以上和25以下

计算25岁以上和以下的用户数量_牛客题霸_牛客网

查询结果:

SELECT IF(age>=25,"25岁及以上","25岁以下") AS age_cut,count(device_id) AS number
FROM user_profile
GROUP BY age_cut;

select 
CASE 
    when age < 25 or age is null then '25岁以下'
    when age >= 25 then '25岁以上'
end as age_cut, count(device_id) number
from user_profile
group by age_cut

如果年龄为空,年龄一行设置为其他

select device_id,gender,
    case 
        when age < 20 then '20岁以下'
        when age >= 20 and age < 24 then '20-24岁'
        when age >= 25 then '25岁及以上' 
        else '其他'
    end as age_cut 
from user_profile 

3.分别获取日期字段中的年、月、日

计算用户8月每天的练题数量_牛客题霸_牛客网

年:year(date) = '2021' 或者  date like ('2021%')

月:month(date)

日:day(date)

4.一个字段多种属性

统计每种性别的人数_牛客题霸_牛客网

 统计每个性别的用户分别有多少参赛者,并且按照人数从小到大排列:

提示:从小到大---asc ,从大到小---desc

select 
   case 
      when profile like '%,male' then 'male'
      when profile like '%,female' then 'female'
   end as gender,
   count(device_id) as number
from user_submit
group by gender
order by number asc

5.删除指定字段中的某一部分内容

例如:http:/ur/bisdgboy777 改为 ur/bisdgboy777

对应题目:提取博客URL中的用户名_牛客题霸_牛客网

  • 替换法 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

6.找出每个学校GPA最低的同学

 结果

select device_id, university,gpa
from user_profile u1
where gpa <= (
                 select min(gpa) 
                 from user_profile u2
                 where u1.university = u2.university
                 group by university
             )
order by university asc

7.去重distinct

查询结果去重_牛客题霸_牛客网

select university from user_profile group by university

或者

SELECT DISTINCT university from user_profile

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值