MySql案例收集

1、if语句。使用场景:筛选出25以下的,或者为空的。分两个组,25岁以上,25岁以下。然后统计年龄段的数量。

  if逻辑块中,给的是判断条件,这里就是,true则执行第一个,false执行第二个。对age分组进行统计。

select if(age<25 or age is null, '25岁以下', '25岁及以上') as age_cut, count(device_id) as number
from user_profile
group by age_cut

2、case语句,可以对列再次重构

==这是查到每个分组的具体人
select
device_id, gender, case when age >= 25 then '25岁及以上' when age <25 and age >= 20 then '20-24岁' else '其他' end as age_cut from user_profile

==也可以统计每个分组数量
select count(device_id) as number, case
when age >= 25 then '25岁及以上'
when age <25 and age >= 20 then '20-24岁'
else '其他' end as age_cut
from user_profile
group by age_cut

 3、对时间日期的截取匹配,这里是匹配的8月份的,统计每天的数量。主要的重点还是在时间函数上面。

select day(date) as day, count(device_id)
from question_practice_detail
where month(date) = 8
group by day

4、对日期时间的筛选,次日的筛选

5、对字符串截取筛选,筛选出性别的的个数。substring是截取从右数第一个逗号后面的所有内容。

select a.sex, count(a.sex)
from (select substring(profile, ',', -1) as sex from user_submit) as a
group by a.sex

6、截取索引之后的内容

select device_id, substr(blog_url, 11) as sbr
from user_submit

截取中间字段:
substr(profile, 12, 2)

 

原文地址:https://www.cnblogs.com/HelloM/p/15602652.html