Hive【Hive(四)函数-单行函数】

函数

函数简介

方便完成我们一些复杂的操作,就好像我们 Spark 中的 UDF 函数,避免用户反复写逻辑。

Hive  提供了大量的内置函数,主要可以分为以下几类:

  • 单行函数
  • 聚合函数
  • 炸裂函数
  • 窗口函数

下面的命令可以查看内置函数的相关信息:

1)查看系统自带的函数

show functions;

2)显示自带的函数的用法

查看函数 upper 的用法(显示函数参数):

desc function upper;

3)详细显示自带的函数的用法

查看函数 upper 的详细用法:

desc function extended upper;

1、单行函数

特点:输入一行,输出一行(或多行)。

按照功能可以分为:

  • 日期函数
  • 字符串函数
  • 集合函数
  • 数学函数
  • 流程控制函数

1.1、算数运算函数

处理常用的 +、-、*、/ 还有 %、&、^、~、|

查询出员工薪资后全部 +100 显示:

select sal+1 from emp; 

1.2、数值函数

1)round:四舍五入

默认不保留小数部分,直接四舍五入为整数。

select round(3.5);  -- 输出4

可以设置第二个参数(控制小数部分的长度):

select round(3.1415,2)  --输出3.14
2)ceil:向上取整
select ceil(3.11);  -- 输出4
3)floor:向下取整
select floor(3.6);    --输出3

1.3、字符串函数

1)substring(str,beg[,len]):截取字符串

解释:从第 beg 个下标对 str 进行截取,共截取 len 长度的字符串。

注意: 下标是从 1 开始的,负数代表取后 beg 位(-4代表取后4位)。

select substring("hello",1);    --返回hello

select substring("hello",1,2);  --返回he

select substring("hello",-4);    --返回ello

select substring("hello",-4,2);    --返回el
2)replace(str1,str2,str3):替换

解释:将字符串 str1 中的子字符串 str2 用 str3 替换。

select replace("hello sxau",'sxau','tylg'); --返回 hello tylg
3)regexp_replace(str1,regex,str2):正则替换

解释:将字符串 str1 中满足正则表达式 regex 的部分用 str2 替换掉。

select regexp_replace("身份证号:141125...","\\d",'*');  --返回 身份证号:******...

注意:这里的正则表达式语法是我们 Java 中的语法,比正常的正则表达式多一个斜杠 \;

4)regexp:正则匹配

解释:满足正则表达式返回 true 否则返回 false。

select '141125' regexp '\\d+';  --返回true
5)repeat(str,count):重复字符串

将字符串 str 重复 count 次。

select repeat('good ',3);    --返回 good good good 
6)split(str,regex):字符串切割

解释:根据正则表达式 regex 将字符串切割开来。

注意:这里返回的是一个数组。

select split("name sex id sal",' '); --返回 ["name","sex","id","sal"]
7)nvl(a,b):替换 null 值

解释:如果 a 不是null,则返回a,否则返回 b。

用法:通常用于判断字段是否为空。

select nvl(null,1);    --返回1
8)concat(str1,str2,...):拼接字符串
select concat('tom','jerry','school');  --返回 tomjerryschool
9)concat_ws:以指定的分隔符拼接字符串
select concat_ws('.','192','168','88','134') --返回 192.168.88.134
10)get_json_object(json_string,path):解析json字符串

JSON 的相关知识可以查看菜鸟教程

解释:解析 json 字符串 json_string,并返回 path 指定的内容。如果输入的 json 字符串无效,那么返回 null。

-- 返回 lyh
select get_json_object('{"name": "lyh",	"friends": ["my","zht"],"students": {"drj": 48,"lyf": 30},"address": {"street": "chang an jie","city":	"beijing","postal_code": 10010}}','$.name');

注意:

  1. 如果是 json 数组,可以通过 '$.[0].name' 的方式获取到下标为 0 的json对象的 name 属性值。
  2. 注意如果 json 字符串内用的是双引号,那么我们的函数参数最好用单引号。

1.4、日期函数

我们的日期时间基本格式为:年-月-日 时:分:秒 

1)unix_timestamp([date_str,format]):返回当前或指定时间的时间戳

解释:将时间字符串 date_str 根据 format 格式解析为时间戳。

注意:一定要注意字符串 date_str 中的间隔符必须要和 format 中一一对应。

select unix_timestamp();    --当前时间的时间戳  1696390814

select unix_timestamp('2023/10/04 11-41-08','yyyy/MM/dd HH-mm-ss');    -- 1696419668
2)from_unixtime(timestamp):将时间戳转为时间

注意:

  1. 这里的参数不是字符串,而是一个数值。
  2. from_unixtime() 只能精确到秒级别。
  3. from_utc_time() 可以精确到毫秒级别,但相应的如果参数是 unix_timestamp 需要*1000 转为毫秒数。
select from_unixtime(1696419668);    --输出 2023-10-04 11:41:08

select from_utc_timestamp(cast(1696419668 as bigint)*1000,'GMT+8');
3)current_date():当前日期

注意:括号可以省略。

select current_date;    --返回 2023-10-04
4)current_timestamp():当前日期的时间,并精确到毫秒
select current_timestamp();     --返回 2023-10-04 11:49:51.696000000
5)month(str):获取日期中的月
select month(current_date());    --返回 10
6)day(str):获取日期的日
select day(current_date());    --返回 4
7)hour(str):获取日期的时
select hour('2023-10-04 11:59:10');    --返回 11
8)datediff(enddate,startdate):两个日期相差的天数
select datediff('2023-10-4','2023-10-1');    --返回 3
9)date_add(startdate,days):日期加天数

注意:有 add 就有 sub,一个加,一个减。

select date_add('2023-10-1',365);    --返回 2024-9-30

select date_sub('2023-10-1',365);    --返回 2022-10-1
10)date_format(date-str,format):将日期字符串转为指定格式的字符串
select date_format('2023-10-4 12:00:05','yyyy年MM月dd日-HH时mm分:ss秒'); --返回2023年10月04日-12时00分:05秒

1.5、流程控制函数

1)case when:条件判断函数
select stu_id,
       course_id,
       score,
       case
        when score>=90 then 'A'
        when score>=80 then 'B'
        when score>=70 then 'C'
        when score>=60 then 'D'
        else '不及格'
       end as grade
from score_info;

如果是等值查询(直接 case 后面跟字段名,when 条件处直接写值即可):

select stu_id,
       course_id,
       score,
       case score
        when 90 then 'A'
        when 80 then 'B'
        when 70 then 'C'
        when 60 then 'D'
       end as grade
from score_info;
2)if:条件判断,类似于 Java 的三元运算符
select stu_id,course_id,
       if(score>60,'及格','不及格') `grade`
from score_info;

1.6、集合函数

集合函数用来处理复杂的数据类型,比如 array、map 和 struct。

1)size :集合中元素的个数
select size(array(1,2,3));    --3
2)map(k1,v1,k2,v2):创建 map 集合
select map('hadoop',1,'spark',1);    --{"hadoop":1,"spark":1}
3)map_keys(map):返回 map 中的 key
select map_keys(map('hadoop',1,'spark',1));    --["hadoop","spark"]
4)map_values(map):返回 map 中的 value
select map_values(map('hadoop',1,'spark',1));    --[1,1]
5)array:声明 array 集合
select array(1,2,3);    --[1,2,3]
6)array_contains(arr,ele):判断 arr 中是否包含元素 ele
select array_contains(array(1,2,3),3);    --true
7)sort_array(arr):将 arr 中的元素排序
select sort_array(array(5,3,4,1));    --[1,3,4,5]
8)struct:声明 struct
select struct('name','age','sex');    --{"col1":"name","col2":"age","col3":"sex"}
9)named_struct():声明 struct 的属性和值
select named_struct('name',"tom",'age',"18",'sex',"男");    --{"name":"tom","age":"18","sex":"男"}

 案例演示

数据准备

create  table  employee(
    name string,  --姓名
    sex  string,  --性别
    birthday string, --出生年月
    hire_date string, --入职日期
    job string,   --岗位
    salary double, --薪资
    bonus double,  --奖金
    friends array<string>, --朋友
    children map<string,int> --孩子
);
insert into employee
  values('张无忌','男','1980/02/12','2022/08/09','销售',3000,12000,array('阿朱','小昭'),map('张小无',8,'张小忌',9)),
        ('赵敏','女','1982/05/18','2022/09/10','行政',9000,2000,array('阿三','阿四'),map('赵小敏',8)),
        ('宋青书','男','1981/03/15','2022/04/09','研发',18000,1000,array('王五','赵六'),map('宋小青',7,'宋小书',5)),
        ('周芷若','女','1981/03/17','2022/04/10','研发',18000,1000,array('王五','赵六'),map('宋小青',7,'宋小书',5)),
        ('郭靖','男','1985/03/11','2022/07/19','销售',2000,13000,array('南帝','北丐'),map('郭芙',5,'郭襄',4)),
        ('黄蓉','女','1982/12/13','2022/06/11','行政',12000,null,array('东邪','西毒'),map('郭芙',5,'郭襄',4)),
        ('杨过','男','1988/01/30','2022/08/13','前台',5000,null,array('郭靖','黄蓉'),map('杨小过',2)),
        ('小龙女','女','1985/02/12','2022/09/24','前台',6000,null,array('张三','李四'),map('杨小过',2));

需求

1)统计每个月的入职人数
select month(replace(hire_date,'/','-')) as month,
       count(*) as cn
from employee
group by
month(replace(hire_date,'/','-'));
2)查询每个人的年龄(年+月)
select name,
       concat(if(month>=0,year,year-1),'年'
           ,if(month>=0,month,12+month),'月') age
from
    (
select name,
       year(current_date())-year(t1.birthday) year,
       month(current_date())-month(t1.birthday) month
from (
    select name,replace(birthday,'/','-') birthday
    from employee
)t1
        )t2;
3)按照薪资进行倒序,如果奖金为 null 置为 0
select name,salary+nvl(bonus,0) 
from employee
order by salary;
4)查询每个人有多少个朋友
select name,size(friends) `朋友` from employee;
5)查询每个人孩子的姓名
select name,map_keys(children) from employee;
6)查询每个岗位男女各多少人
select job,
       sum(if(sex='男',1,0)) male,
       sum(if(sex='女',1,0)) female
from employee
group by job;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
一、关系运算: 4 1. 等值比较: = 4 2. 不等值比较: 4 3. 小于比较: < 4 4. 小于等于比较: 5 6. 大于等于比较: >= 5 7. 空值判断: IS NULL 5 8. 非空判断: IS NOT NULL 6 9. LIKE比较: LIKE 6 10. JAVA的LIKE操作: RLIKE 6 11. REGEXP操作: REGEXP 7 二、数学运算: 7 1. 加法操作: + 7 2. 减法操作: - 7 3. 乘法操作: * 8 4. 除法操作: / 8 5. 取余操作: % 8 6. 位与操作: & 9 7. 位或操作: | 9 8. 位异或操作: ^ 9 9.位取反操作: ~ 10 三、逻辑运算: 10 1. 逻辑与操作: AND 10 2. 逻辑或操作: OR 10 3. 逻辑非操作: NOT 10 、数值计算 11 1. 取整函数: round 11 2. 指定精度取整函数: round 11 3. 向下取整函数: floor 11 4. 向上取整函数: ceil 12 5. 向上取整函数: ceiling 12 6. 取随机数函数: rand 12 7. 自然指数函数: exp 13 8. 以10为底对数函数: log10 13 9. 以2为底对数函数: log2 13 10. 对数函数: log 13 11. 幂运算函数: pow 14 12. 幂运算函数: power 14 13. 开平方函数: sqrt 14 14. 二进制函数: bin 14 15. 十六进制函数: hex 15 16. 反转十六进制函数: unhex 15 17. 进制转换函数: conv 15 18. 绝对值函数: abs 16 19. 正取余函数: pmod 16 20. 正弦函数: sin 16 21. 反正弦函数: asin 16 22. 余弦函数: cos 17 23. 反余弦函数: acos 17 24. positive函数: positive 17 25. negative函数: negative 17 五、日期函数 18 1. UNIX时间戳转日期函数: from_unixtime 18 2. 获取当前UNIX时间戳函数: unix_timestamp 18 3. 日期转UNIX时间戳函数: unix_timestamp 18 4. 指定格式日期转UNIX时间戳函数: unix_timestamp 18 5. 日期时间转日期函数: to_date 19 6. 日期转年函数: year 19 7. 日期转月函数: month 19 8. 日期转天函数: day 19 9. 日期转小时函数: hour 20 10. 日期转分钟函数: minute 20 11. 日期转秒函数: second 20 12. 日期转周函数: weekofyear 20 13. 日期比较函数: datediff 21 14. 日期增加函数: date_add 21 15. 日期减少函数: date_sub 21 六、条件函数 21 1. If函数: if 21 2. 非空查找函数: COALESCE 22 3. 条件判断函数:CASE 22 4. 条件判断函数:CASE 22 七、字符串函数 23 1. 字符串长度函数:length 23 2. 字符串反转函数:reverse 23 3. 字符串连接函数:concat 23 4. 带分隔符字符串连接函数:concat_ws 23 5. 字符串截取函数:substr,substring 24 6. 字符串截取函数:substr,substring 24 7. 字符串转大写函数:upper,ucase 24 8. 字符串转小写函数:lower,lcase 25 9. 去空格函数:trim 25 10. 左边去空格函数:ltrim 25 11. 右边去空格函数:rtrim 25 12. 正则表达式替换函数:regexp_replace 26 13. 正则表达式解析函数:regexp_extract 26 14. URL解析函数:parse_url 26 15. json解析函数:get_json_object 27 16. 空格字符串函数:space 27 17. 重复字符串函数:repeat 27 18. 首字符ascii函数:ascii 28 19. 左补足函数:lpad 28 20. 右补足函数:rpad 28 21. 分割字符串函数: split 28 22. 集合查找函数: find_in_set 29 八、集合统计函数 29 1. 个数统计函数: count 29 2. 总和统计函数: sum 29 3. 平均值统计函数: avg 30 4. 最小值统计函数: min 30 5. 最大值统计函数: max 30 6. 非空集合总体变量函数: var_pop 30 7. 非空集合样本变量函数: var_samp 31 8. 总体标准偏离函数: stddev_pop 31 9. 样本标准偏离函数: stddev_samp 31 10.中位数函数: percentile 31 11. 中位数函数: percentile 31 12. 近似中位数函数: percentile_approx 32 13. 近似中位数函数: percentile_approx 32 14. 直方图: histogram_numeric 32 九、复合类型构建操作 32 1. Map类型构建: map 32 2. Struct类型构建: struct 33 3. array类型构建: array 33 十、复杂类型访问操作 33 1. array类型访问: A[n] 33 2. map类型访问: M[key] 34 3. struct类型访问: S.x 34 十一、复杂类型长度统计函数 34 1. Map类型长度函数: size(Map) 34 2. array类型长度函数: size(Array) 34 3. 类型转换函数 35

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

让线程再跑一会

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值