文章目录
整理SQL
常见
1. round(value,n)
value:数值。可为储存数值的字段
n:小数点位数,为自然数
//保存一位小数
select
count(gender) as male_num,
round(avg(gpa), 1) as avg_gpa
from
user_profile
where
gender = 'male'
2. group by…having
having相当于条件筛选,与where筛选不同,having是对于group by对象进行筛选
//取出平均发贴数低于5的学校或平均回帖数小于20的学校。
select
university,
round(avg(question_cnt), 1) as avg_question_cnt,
round(avg(answer_cnt), 1) as avg_answer_cnt
from
user_profile
group by
university
having
avg_question_cnt < 5
or avg_answer_cnt < 20
3. case…when…then…end
select
device_id,
gender,
(
case
when age < 20 then '20岁以下'
when age between 20 and 24 then '20-24岁'
when age >= 25 then '25岁及以上'
else '其他'
end
) as age_cut
from
user_profile
4. year() month() day()
取时间字段的年、月、日值
5. date_add()
date_add(date,interval expr type)
- date 参数是合法的日期表达式
- expr 参数是希望添加的时间间隔
- type可填:hour day month
select DATE_ADD(now(),INTERVAL 2 DAY)
6. substring_index(s, start, length)
- s:要处理的字符串
- start:分隔符
- length:计数
substring_index(profile, ‘,’, -1)取出性别
执行
1. group by 、having、where 、order by
按照如下顺序执行:where, group by, having, order by
- where将原始记录中不满足条件的记录删除(所以应该在where语句中尽量的将不符合条件的记录筛选掉,这样可以减少分组的次数)
- group by关键字后面指定的分组条件将筛选得到的视图进行分组
- having关键字后面指定的筛选条件,将分组视图后不满足条件的记录筛选掉
- order by语句对视图进行排序
2. join、inner join、left join、right join、outer join
https://blog.csdn.net/qyj123456789/article/details/123589620
3. union、union all
- union由两条以上的SELECT语句组成,语句之间用关键字union分割
- union中的每个查询必须包含相同的列、表达式或聚集函数
- 取出来的数据不需要去重,使用union all