SparkSQL-内置函数

        数值函数

1. round(x, [d]):对x保留d位小数,同时产生四舍五入
select round(1.26, 1);
OK
1.3

2. format_number(x, d):对x进行格式化,同时支持四舍五入,整数部分每隔d位,用逗号隔开
select format_number(1111111111, 3);
OK
1,111,111,111.000

3. floor(x):获取一个不大于x的整数
select floor(3.55);
OK
3

4. ceil(x):获取一个不小于x的整数
select ceil(3.55);
OK
4

5. rand():产生0~1的随机数

        数学函数

1. abs(x):取绝对值
select abs(-1);
OK
1

2. pow(a, b):获取a的b次幂

3.sqrt(x) :平方根

        条件判断函数

1. if(expr1,expr2,expr3):如果expr1为true,返回expr2,否则返回expr3

2. case when: 多条件表达式
select 
age,
case age
when 24 then '少年'
when 25 then 'xxx'
else '老年'
from
xxx

        日期函数

1. current_date : 获取当前日期,yyyy-MM-dd
2. current_timestamp:获取当前时间戳,yyyy-MM-dd HH:mm:ss.SSS
3. add_months(start_date, num_months):返回start_date之后num_months月之后的日期
4. date_add(start_date,num_days):返回start_date之后num_days天之后的日期
5. date_sub(start_date,num_days):返回start_date之后num_days天之前的日期
6. next_day(start_date, day_of_week):返回start_date之后的最接近day_of_week的日期
7. dayofmonth(date):返回date对应月份的第几天
8. weekofyear(date):返回date对应的日期是这年中的第几周
9. year/minute/hour/day/month
10. datediff(date1,date2):返回date1和date1之间的差值,以天为单位
11. date_format(date, format):返回date以format的格式化输出
12. to_unix_timestamp(date):获取date对应的unix时间
13. from_unixtime(unix_time, format):将unix_time转换format的格式化输出
14. to_date(datetime):获取datetime中的date部分

        字符串函数

1. length(str):返回str的长度
2. instr(str, substr):返回str中的substr中的index
select instr("wang jun jie hen shuai", "shuai");
OK
18

3. substr/substring(str, pos[,len]):从str的pos处开始截取len个长度,如果没有len就截取剩下的所有
4. substring_index(str, delim, count):将str使用delim切割,返回count个使用delim拼接的子字符串
5. concat(str1, str2):拼接字符串
6. concat_ws(sepator, str1,str2):使用指定分隔符来拼接字符

        统计函数

sum()
max()
min()
avg()
count()

         特殊函数

1. array:返回数组
2. collect_set:返回一个元素不重复的set集合
3. split :拆分
4. explode
5. cast(type1 as type2)

        WordCount用内置函数实现

select
tmp.word,
count(1) counts
(
select 
    explode(split(line, "\\s+")) word
    from
xxx
) tmp
group by tmp.word
order by counts desc, tmp.word

猜你喜欢

转载自blog.csdn.net/dafsq/article/details/129637739