一、字段處理函數
字符串處理函數:
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);
三、練習舉例
--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 ('安徽省','江蘇省');