上期讲解了MySQL的一些基础知识(面试必备sql知识点——MySQL基础)
本期继续深化知识点,基于基础,做进一步延伸。学习就是个不断反刍的过程,将碎片化的知识,搭建成完整的框架体系,才能够真正掌握。如果对你有帮助,建议点赞收藏!
内容大纲:
一、条件
CASE表达式
case 函数的格式为:case when 判断表达式 then 表达式 else 表达式 end
else 可省略,end不可省略。
- 连续数值转离散分类
--借款金额分组
select (case
when 借款金额>0 and 借款金额 <=5000 then '0-5000'
when 借款金额>5000 and 借款金额 <=10000 then '5000-10000'
when 借款金额>10000 and 借款金额 <=20000 then '10000-20000'
when 借款金额>20000 and 借款金额 <=50000 then '20000-50000'
else'50000以上' end )as "借款金额区间"
from table1
- 行列转换
SELECT 学号,
sum(case 课程号 when '001' then 成绩 else 0 end ) as '课程001',
sum(case 课程号 when '002' then 成绩 else 0 end ) as '课程002',
sum(case 课程号 when '003' then 成绩 else 0 end ) as '课程003'
from score
GROUP BY 学号;
if函数
if函数格式为:if(条件,条件为真时的值,条件为假时的值)
如上述行列转换也可以这样写,得到的结果一致。
SELECT
sum(if(课程号=001,成绩,0))as '课程001',
sum(if(课程号=002,成绩,0))as '课程002',
sum(if(课程号=003,成绩,0))as '课程003'
from score
GROUP BY 学号;
但借款金额的分组就不如case when 书写方便了,但在计数算比列方面,if的写法可以减少查询的嵌套。
二、字符串函数
常用
- concat 字符串拼接 —— concat(字符串,字符串···)
SELECT concat(str1,str2) as string
from str;