好用到不行的 SparkSQL 开窗函数

好用到不行的 [Spark] SQL开窗函数

  • To use window functions, users need to mark that a function is used as a window function by either
    Adding an OVER clause after a supported function in SQL, e.g. avg(revenue) OVER (…); or
    (SparkSQL) Calling the over method on a supported function in the DataFrame API, e.g. rank().over(…).

    如: rank() over( partition by ... order by ... ) ranks

Ranking:

	rank -- 跳跃排序
	dense_rank -- 连续排序
	row_number
	percent_rank
	ntile 
	
	ntile(expr) over([partition_clause] order_by_clause) 
		可以看成是:它把有序的数据集合平均分配到指定的数量(expr)个桶中,将桶号分配给每一行。
		如果不能平均分配,则较小桶号的桶分配额外的行,并且各个桶中能放的行数最多相差1。
	
	使用rank() over()时,用nulls last将null值(null最大,避免在前面有null值)排在最后面。		  
		rank over(partition by empno order by sales desc nulls last)

aggregate:

	count
    max
    min
    sum
    avg
    
	少数据量时,如直接计算各部门当前月及累计销售额:
	  select distinct 
	  		empno,month
	  		,sum(sales) over(partition by empno,month) sum_sales
	  		,sum(sales) over(partition by empno order by month) acc_sum_sales 
	  from Table

analytic:

	cume_dist
    first_value
    last_value
    lag
    lead

参考资料:

  1. Introducing Window Functions in Spark SQL 可见链接: https://databricks.com/blog/2015/07/15/introducing-window-functions-in-spark-sql.html
  2. [Oracle查询优化改写 技巧与案例 有教无类 落落 著]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值