mysql 属性函数_4-MySQL函数(字段处理函数&条件判断函数)

一、字段处理函数

字符串处理函数:

concat(field1,field2 …… )

substr(str,pos,len)

replace(str,old_str,new_str)【Hive:regexp_replace('2020-03-15','-','') 】

日期处理函数:

current_date():返回当前日期;

date_add(日期格式,INTERVAL 数字 day/week)/date_sub(日期格式,INTERVAL 数字 day/week);

datediff(date1,date2)【date1-date2】;

数学函数:

round(x,y):四舍五入,返回对x保留y小数位的数字;

二、条件判断函数

if 函数:单条件判断

语法:if(condition, value_if_true, value_if_false)

特点:使用规则简单清晰,但多条件判断写法不够直观;

eg:高考分数>620,就返回A,否则返回B(另一种:如果是江苏省,高考分数>600,就返回A,否则……)

case when 函数:多条件判断

简单函数:CASE [col_name] WHEN [value1] THEN [result1]…ELSE [default] END

搜索函数:CASE WHEN [expr] THEN [result1]…ELSE [default] END

注意两点:1、THEN后面没有逗号;2、结尾有END

eg:查学生数据:针对安徽学生,高考分数>620,返回A,否则返回B;字段:学号,姓名,籍贯,类别(A或B);

三、练习举例

81e66ca38747

表例

--hive中别名用··来区分

--1.查询学生专业数据;字段:学号,姓名,学院,专业,格式:学号-姓名-学院-专业;

select

concat(stu_id,'-',name,'-',college,'-',major) as 学生信息

from student_info;

--2.问题1返回的数据,把“专业”字段里“专业”二字去掉,其他字段和格式都不变;

--eg:问题1返回:学号xxx-姓名-xxx学院-xxx专业:改成:学号xxx-姓名-xxx学院-xxx

select

concat(stu_id,'-',name,'-',college,'-',replace(major,'专业','')) as 学生信息

from student_info;

--3.查询学生入学的月份;字段:学号,姓名,入学月份(年-月);

select

stu_id as 学号,

name as 姓名,

substr(entry_date,1,7) as 入学月份

from student_info;

--4.查询学生已经入学多少天了;字段:学号,姓名,入学多少天;

select

stu_id as 学号,

name as 姓名,

datediff(current_date(),entry_date) as 入学天数

from student_info;

--5.这届学生的入学日期都是2016-09-01,60天后举办运动会,该怎么查询那天日期是多少?

select

distinct date_add(entry_date,INTERVAL 60 day) as 运动会日期

from student_info;

--6.江苏的高考比较难,希望对这届江苏学生的高考分数*1.1,保留1位小数;字段:学号,姓名,高考分数;

select

stu_id as 学号,

name as 姓名,

round(gk_score*1.1,1) as 高考分数

from student_info;

--7.将学生分班,高考分数小于610,进C班;小于630,进B班,否则进A班;字段:学号,姓名,高考分数,班级(用if);

select

stu_id as 学号,

name as 姓名,

gk_score as 高考分数,

if(gk_score<610,'C',if(gk_score>=630,'A','B')) as 班级

from student_info;

--8.查询来自安徽省、江苏省的学生,年龄分段情况:(用case when);字段:学号,姓名,年龄段;

--小于等于18岁,返回Y

--大于等于19,小于等于20,返回M

select

stu_id as 学号

,name as 姓名

,age as 年龄

,case when age between 19 and 20 then 'M'

when age<=18 then 'Y'

end as 年龄段

from student_info

where from_where in ('安徽省','江苏省');

--离散值(需要全部枚举出来)举例

select

stu_id

,name

,case age

when 18 then 'M'

when 19 then 'Y'

when 20 then 'Y'

else 'other'

end as stu_age

from student_info

where from_where in ('安徽省','江苏省');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值