sparksql2.0整理-自用

版权声明:转载请注明出处----------谢谢! https://blog.csdn.net/sinat_36755318/article/details/78922737

各种运算符

算术运算符:                                                                                         

| %     取模运算    (求最大公约数)                    
| *     乘                   
| +     加                    
| -     减                    
| /     除


关系运算符:
| <     小于                      
| <=    小于等于                  
| <=>   'A'<=>'B'得0和'a'<=>'a'得1     'a' <=> NULL 得0   NULL<=> NULL 得出 1
| >     大于                      
| >=    大于等于                  


逻辑运算符:
| !     逻辑非 
| |                           
| ~                           


位运算符:
| ^     按位异或                    
| &     双目运算符:将两个表达式的值按二进制位展开,对应的位(bit)按值进行“与”运算,结果保留在该位上  


赋值运算符:                      
| =                           
| ==  




数学函数:             
| abs(x)        绝对值                 
| acos(x)       --返回X的反余弦。X值的范围必须在-1和1之间,否则返回 NULL                 
| atan 
| asin
| sin
| cos
| tan                         
| tanh
| atan2
| rand()    rand(Int seed)   double                     
| ceil          --3.2   ->  4                     
| ceiling
| floor         --3.2   ->  3
| round 
| exp(d)    --e的d幂次方
| ln 
| log                         
| log10                       
| log1p                       
| log2
| pow                         
| power
| sqrt      --平方根
| cbrt       --立方根    
| bin
| conv(BIGINT num,INT from_base,INT to_base)
| hex
| base64
| unbase64                    
| unhex 
| pmod(INT i1,Int i2)   --i1对i2取模       INT、double
| radians   --角度值转弧度值
| degrees   --弧度值转角度值
| positive          --  \+i
| negative          --  \+d
| sign(double d)    --d是正数,返回float1.0,负数返回-1.0,否则返回0.0
| e
| pi


日期/时间函数 (见《hive sql常用整理-自用 》)
| add_months(date,months)   --添加月份(无论带不带时间,都只返回日期)
| to_date                --返回日期"2017-12-01"    to_date(“1970-01-01 00:00:00″) = “1970-01-01″
| year
| month
| day
| hour
| second
| minute
| unix_timestamp(STRING date)      --转换成unix时间戳,格式必须是(yyyy-MM-dd HH:mm:ss),如果格式不对返回0,   unix_timestamp('2017-12-01 11:11:11') = 数字
        unix_timestamp(STRING date,STRING pattern)   --同上,只是指定格式    unix_timestamp('2017-12-01','yyyy-MM-dd') = 数字 
        unix_timestamp()        --获取当前时间戳
| to_unix_timestamp
| to_utc_timestamp
| timestamp       
| weekofyear 
| date                        
| date_add                    
| date_format                 
| date_sub                    
| datediff('string enddate','string startdate')     --两个时间参数的日期之差
| dayofmonth                  
| dayofyear
| next_day                        
| months_between
| last_day      --返回本月最后一天
| trunc               --TRUNC(date,[fmt])   --select trunc('2017-12-03','mm');      //2017-12-01    当年第一天
                        --select trunc('2017-12-03','yyyy');    //2017-01-01        当月第一天
 

聚合函数:

| collect_set(col)           --返回集合col元素重排后的数组,把下面的去重

collect_set(0) 具有稳定性排序,以后每次跑都是同一个,但性能差一点
       
         first(0)    不是稳定性排序,随机的,但性能好一些,所以影响的关键字段最好具有稳定性

| collect_list            --collect_list函数返回的类型是array< ? >类型,?表示该列的类型 (列表)
                        例如:select id,collect_list(name) from test_yxl group by id order by id;          
| approx_count_distinct     --近似去重统计,数据量大时结果会与distinct有偏差  
| count(*)  --计算包含null值的行
       count(expr) count(distinct expr) --计算非null值的行
| covar_pop(col)  --返回一组数值的协方差                
| covar_samp(col) --返回一组数值的标准样本方差
| var_pop(col)      --返回集合col的一组数值的方差                    
| var_samp(col)     --返回集合col的一组数值的样本方差             
| variance(col)     --返回集合col的一组数值的方差
| corr(col1,col2)      --返回两组数值的相关系数
| stddev                 --偏差     
| stddev_pop                  
| stddev_samp


表生成函数:
| explode
        例如:select explode(split(concat_ws(',','1','2','3','4'),','))  

        例如:select id,name,explode(split(concat_ws(',','1','2','3','4'),',')) as n from test_yxl;分割一个拼接字段再拓展成几行(stack做不到)

--原来每一行拓展成4行

id1,name1,1

id1,name1,2

id1,name1,3

id1,name1,4

...

| inline(ARRAY STRUCT)    --将结构体数组提取出来并插入到表中
| parse_url     --返回url解析出来的每部分数据,返回的是元、组
| stack(INT n,col1,....,colM)   --把M列转换成N行,每行有M/N个字段,n必须是常数


分析函数 (与group by同时使用)和窗口函数(与over子句同时使用):             
| grouping       --根据不同的维度组合进行聚合,等价于将不同维度的group by结果集进行UNION ALL             
| cube           --根据GROUP BY的维度的所有组合进行聚合,且包含一行是所有group by字段同时为空的情况 
| rollup         --是CUBE的子集,以最左侧的维度为主,从该维度进行层级聚合
| grouping_id    --需要与grouping、with cube、with rollup之类的分析函数同时使用,只是多输出一列分组集合的编号   


| lag(col,n,DEFAULT)    --用于统计窗口内往上第n行值--第一个参数为列名,第二个参数为往上第n行(可选,默认为1),第三个参数为默认值(当往上第n行为NULL时候,取默认值,如不指定,则为NULL,字段类型需要与第一个参数相同,否则位NULL)
| lead      --与lag相反,往下统计


| row_number over(...)   --从1开始,按照顺序,生成分组内记录的序列
| rank() over(...)       --生成数据项在分组中的排名,排名相等会在名次中留下空位
| dense_rank() over(...) --生成数据项在分组中的排名,排名相等会在名次中不会留下空位                 
| sum() over(...)
| avg() over(...)
| max() over(...)
| min() over(...)                     
| first_value   --取分组内排序后,截止到当前行,第一个值
| first         --与first_value用法相同
| last_value    --取分组内排序后,截止到当前行,最后一个值
| last          --与last_value用法相同
| ntile --用于将分组数据按照顺序切分成n片,返回当前切片值(不支持rows between) <统计某个id分组后的前几分之几的部分,结合case when>
| cume_dist     --小于等于当前值的行数/分组内总行数
| percent_rank  --分组内当前行的RANK值-1/分组内总行数-1


其他函数
| ascii(s)       --返回字符串s中首个ASCII字符的整数值                                       
| like      --通配符       select "aaaaaa" like "%aa%"
| rlike     --正则         select "aaaaaa" rlike ".*aaa"
| rpad( string1, padded_length, [ pad_string ] )    --自动补全
| lpad( string1, padded_length, [ pad_string ] )
| rtrim     --去掉右边空格
| ltrim     --去掉左边空格    
| trim      --去掉前后空格
| upper     --转换成大写            
| ucase     --转换成大写
| lower     --转换成小写
| lcase     --转换成小写
| initcap   --将每个单词的第一个字母大写,其它字母变为小写返回.               
| concat(string A, string B…)   --连接多个字符串,合并为一个字符串,可以接受任意数量的输入字符串
                                --任何字符与null连接都是NULL                    
| concat_ws(string SEP, string A, string B…)    
                --带分隔符字符串连接函数,该函数仅支持string和array< string > 所以对于该列不是string的列,先转为string
                        例如:select concat_ws(',','abc','def','gh') from lxw_dual;返回abc,def,gh                 
| decode    --使用指定字符集...
| encode 
| find_in_set   --返回在以逗号分割的字符串中s出现的位置,如果没有找到则返回null
| format_number     --转换格式               
| format_string               
| from_unixtime               
| from_utc_timestamp
| get_json_object   --从给定路径上的json字符串中抽取出json对象,并返回这个对象的json字符串,非法则为null
| in
| instr(STRINGstr str,STRING substr)     --查找字符串str中子字符串substr第一次出现的位置
| length        --计算字符串长度
| size      --返回元素个数        select size(array(8,2,9,1));    //返回4
| locate(STRING substr,STRING str[,INT pos])    --查找在字符串str中的pos位置后字符串substr第一次出现的位置
| printf
| regexp_extract(str, regexp[, idx])  --通过下标返回正则表达式指定的部分            
| regexp_replace(string A, string B, string C)    --正则表达式替换函数 字符串A中的B字符被C字符替代 
| split(string str, string pat)    --将字符串转换为数组,以pat为分隔
| repeat(STRING s,INT n)    --重复输出n次字符串s
| reverse       --反转字符串
| sentences     --将输入字符串s转换成句子数组,每个句子又由一个单词数组构成
| space(n)     --返回n个空格 
| str_to_map    --将字符串s按照指定分隔符转换成Map,第一个参数是输入的字符串,第二个是键值对之间的分隔符,第三个是键和值之间的分隔符
|substr(string A, int start) 或者 substring(string A, int start) --字符串截取函数,
   例:select substr('akojjoibcde',3);  --返回ojjoibcde
   例:select substring('ancdefghijklmn',4,8);    --返回 defghijk
| substring                   
| substring_index
| translate


| or      
| and 
| isnotnull                   
| isnull
| coalesce      例:select coalesce(null,null,1); 返回1
                例:select coalesce(null,'yu',1); 返回yu
| if                          
| ifnull
| nvl
| when                        
| window
| not 


| int                                                            
| bigint 
| tinyint 
| boolean
| float  
| double
| decimal                                          
| binary 
| string
| array
| sort_array
| array_contains                      
      


      
| bround                             


| assert_true                     
                       


                       
| cosh                        
| crc32                                      
| current_database            
| current_date                
| current_timestamp           
                    
                     
| elt                         
| expm1                       
| factorial                   
                      
| greatest       
| hash                        
| hypot                       
                     
| input_file_name             
                        
| isnan                       
                      
| java_method                 
| json_tuple                  
| kurtosis                                        
| least                       
| levenshtein 
| map                         
| map_keys                    
| map_values                  
| mask                        
| mask_first_n                
| mask_hash                   
| mask_last_n                 
| mask_show_first_n           
| mask_show_last_n                                    
| md5                         
| mean                                                                     
| monotonically_increasing_id             
| named_struct                
| nanvl                       
                        
| now                                             
| nullif                      
                         
| nvl2                        
                                                 
| posexplode                                        
| quarter                                             
| randn                                             
| reflect                                          
| rint                                           
                       
| shiftleft       --左移位            
| shiftright                  
| shiftrightunsigned                                 
| signum                                              
| sinh                                              
| skewness                    
| smallint                                    
| soundex                                          
| spark_partition_id                                
| std                                           
                      
| struct                                              
                   
                                             
   
| sha                         
| sha1                        
| sha2 


xml:                   
| xpath                       
| xpath_boolean               
| xpath_double                
| xpath_float                 
| xpath_int                   
| xpath_long                  
| xpath_number                
| xpath_short                 
| xpath_string                
                


另:
1. SQL Server中使用EXCEPT运算符可以实现集合差操作,即从左查询中返回右查询没有找到的所有非重复值
EXCEPT 用于查询包含在A语句的结果集中但不包含在B语句的结果集中的结果 
                --通过比较行来确定非重复值时,两个NULL值被视为相等
                --EXCEPT返回的结果集的列名与操作数左侧的查询返回的列名相同
     explain  select a from table1 except select a from table2 ==> left anti join
INTERSECT   两个表的交运算
        SELECT * FROM TableA 
        EXCEPT 
        SELECT * FROM TableB 
        INTERSECT 
        SELECT * FROM TableC
  --优先级:括号中的表达式 > INTERSECT操作符 > 基于在表达式中的位置从左到右求值的EXCEPT和UNION运算
  
  select a from table1 INTERSECT select a from table2
  
  

  ****************建表和数据*******************

 CREATE EXTERNAL TABLE `test_yxl`(`id` int, `name` string, `val` double)
PARTITIONED BY (`p_provincecode` int, `p_date` string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
STORED AS textfile
LOCATION 'hdfs://nameservice/路径/'
)


数据

3,au,100.0
3,bob,78.0
6,pp,92.0
8,we,57.0
8,jy,27.0
7,ha,27.0
6,,85.0
3,tom,30.0
10,we,24.0
12,,100.0
3,pp,92.0
,jay,49.0
8,jy,27.0
8,jy,28.0

  
*****************************************************************分析函数*************************************************************
GROUP BY a, b, c WITH CUBE
GROUP BY a, b, c WITH ROLLUP
GROUP BY a, b, c GROUPING SETS (**** )
lag


==============grouping sets==============
select
    name,
    val,
    count(distinct id) as uv,
    grouping_id() as groupid
from test_yxl
group by name,val 
grouping sets (name,val,(name,val)) 
order by groupid


select
    name,
    val,
    count(distinct id) as uv,
    grouping_id() as groupid
from test_yxl
group by name,val 
grouping sets (name,val,(name,val),()) 
order by groupid


==============with cube==============
select
    name,
    val,
    count(distinct id) as uv,
    grouping_id() as groupid
from test_yxl
group by name,val 
with cube
order by groupid


select
    id,
    name,
    val,
    count(distinct p_provincecode) as uv,
    grouping_id() as groupid
from test_yxl
group by id,name,val
with cube
order by groupid


select
    id,
    name,
    val,
    count(p_provincecode) as uv,
    grouping_id() as groupid
from test_yxl
group by id,name,val
with cube
order by groupid


==============with rollup==============
select
    id,
    name,
    val,
    count(distinct id) as uv,
    grouping_id() as groupid
from test_yxl
group by id,name,val 
with rollup
order by groupid


==============lag==============
select
    id,
    name,
    val,
    row_number() over(partition by id order by val desc ) as row_r,
    lag(val,1,8888.88) over(partition by id order by val desc ) as lag1,
    lag(val,2) over(partition by id order by val desc ) as lag2
from test_yxl


select
    id,
    name,
    val,
    row_number() over(order by val desc ) as row_r,
    lag(val,1,8888.88) over(order by val desc ) as lag1,
    lag(val,2) over(order by val desc ) as lag2
from test_yxl




*****************************************************************窗口函数*************************************************************
row_number、rank、dense_rank、sum、avg、min、max、ntile、first_value


==============row_number、rank、dense_rank==============
select
    id,
    name,
    val,
    row_number() over(partition by id order by val desc) as level1
from test_yxl


select
    id,
    name,
    val,
    row_number() over(order by val desc) as row_level,
    rank() over(order by val desc) as rank_level,
    dense_rank() over(order by val desc) as dense_level
from test_yxl
    
==============sum、avg、min、max==============
select
    id,
    name,
    sum(val) over(partition by id order by name) as sum1,
    sum(val) over(partition by id order by name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum2,
    sum(val) over(partition by id) as sum3,
    sum(val) over(partition by id order by name ROWS BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING) as sum4,
    max(val) over(partition by id order by name) as max1,
    max(val) over(partition by id order by name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as max2,
    max(val) over(partition by id) as max3,
    max(val) over(partition by id order by name ROWS BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING) as max4
from test_yxl


==============ntile==============
select
    id,
    name,
    val,
    ntile(2) over(partition by id order by val) as ntile1,
    ntile(3) over(partition by id order by val) as ntile2,
    ntile(4) over(order by val) as ntile3
from test_yxl
order by id,name


--结合case when
select
    id,
    name,
    val,
    case ntile(4) over(order by val desc )
    when 1 then "优"
    when 2 then "良"
    when 3 then "及格"
    when 4 then "惨"
    end as level
from test_yxl
order by id,name


==============first_value==============
select
    id,
    name,
    val,
    row_number() over(partition by id order by val desc) as level1,
    first_value(name) over(partition by id order by val desc) as first_1
from test_yxl


==============last_value==============
--不对
select
    id,
    name,
    val,
    row_number() over(partition by id order by val desc) as level1,
    last_value(name) over(partition by id order by val desc) as last_1
from test_yxl




--如果不指定ORDER BY且没有row_number(),则默认按照记录在文件中的偏移量进行排序,会出现错误的结果
select
    id,
    name,
    val,
    last_value(name) over(partition by id ) as last_1
from test_yxl


select
    id,
    name,
    val,
    row_number() over(partition by id order by val desc) as level1,
    first_value(name) over(partition by id order by val desc) as first_1,
    last_value(name) over(partition by id order by val desc ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as last_1
from test_yxl


==============cume_dist==============
select
    id,
    name,
    val,
    cume_dist() over(order by val) as cume_1,
    cume_dist() over(partition by id order by val) as cume_2
from test_yxl


==============percent_rank==============
select
    id,
    name,
    val,
    percent_rank() over(order by val) as percent_1,
    rank() over(order by val) as rank_1,
    sum(1) over(partition by null) as sum_1,
    percent_rank() over(partition by id order by val) as percent_2
from test_yxl

猜你喜欢

转载自blog.csdn.net/sinat_36755318/article/details/78922737
今日推荐