SQL优化:hive中的over和各个函数综合应用

1.使用over子句与rows_number()以及聚合函数进行使用,可以进行编号以及各种操作。而且利用over子句的分组效率比group by子句的效率更高。

2.在订单表(order)中统计中,生成这么每一条记录都包含如下信息:“所有订单的总和”、
“每一位客户的所有订单的总和”、”每一单的金额“


#代码如下
select 
customerID,
SUM(totalPrice) over() as AllTotalPrice,
SUM(totalPrice) over(partition by customerID) as cusTotalPrice,
totalPrice
from OP_Order

关键点:使用了sum() over() 这个开窗函数 

3.在订单表(order)中统计中,生成这么每一条记录都包含如下信息:“所有订单的总
和(AllTotalPrice)”、“每一位客户的所有订单的总(cusTotalPrice)”、”每一单
的金额(totalPrice)“,”每一个客户订单的平均金额(avgCusprice)“,”所有客户的所
有订单的平均金额(avgTotalPrice)“,"客户所购的总额在所有的订单中总额的比
例(CusAllPercent)","每一订单的金额在每一位客户总额中所占的比例(cusToPercent)"。


代码如下:
with tabs as
 (
  select 
 customerID,
 SUM(totalPrice) over() as AllTotalPrice,
 SUM(totalPrice) over(partition by customerID) as cusTotalPrice,
 AVG(totalPrice) over(partition by customerID) as avgCusprice,
 AVG(totalPrice) over() as avgTotalPrice,
 totalPrice
 from OP_Order
 )
 select 
 customerID,
 AllTotalPrice,
 cusTotalPrice,
 totalPrice,
avgCusprice,
avgTotalPrice,
 cusTotalPrice/AllTotalPrice as CusAllPercent,
 totalPrice/cusTotalPrice as cusToPercent 
 from tabs


4.在订单表(order)中统计中,生成这么每一条记录都包含如下信息:“所有订单的
总和(AllTotalPrice)”、“每一位客户的所有订单 的总(cusTotalPrice)”、
”每一单的金额(totalPrice)“,”每一个客户订单的平均金额(avgCusprice)“,”
所有客 户的所有订单的平均金额(avgTotalPrice)“,"订单金额最小值(MinTotalPrice)
","客户订单金额最小值(MinCusPrice)","订单金额最大值(MaxTotalPrice)",
"客户订单金额最大值(MaxCusPrice)","客户所购的总额在所有的订单中总额的
比例(CusAllPercent)","每一订单的金 额在每一位客户总额中所占的比例(cusToPercent)"。


关键:利用over子句进行操作。


with tabs as
 (
  select 
 customerID,
 SUM(totalPrice) over() as AllTotalPrice,
 SUM(totalPrice) over(partition by customerID) as cusTotalPrice,
 AVG(totalPrice) over(partition by customerID) as avgCusprice,
 AVG(totalPrice) over() as avgTotalPrice,
 MIN(totalPrice) over() as MinTotalPrice,
 MIN(totalPrice) over(partition by customerID) as MinCusPrice,
 MAX(totalPrice) over() as MaxTotalPrice,
 MAX(totalPrice) over(partition by customerID) as MaxCusPrice,
 totalPrice
 from OP_Order
 )
 select 
 customerID,
 AllTotalPrice,
 cusTotalPrice,
 totalPrice,
 avgCusprice,
 avgTotalPrice,
 MinTotalPrice,
 MinCusPrice,
 MaxTotalPrice,
 MaxCusPrice,
 cusTotalPrice/AllTotalPrice as CusAllPercent,
 totalPrice/cusTotalPrice as cusToPercent 
 from tabs

今天遇到这样一个需求场景,要取出 每一种分类(a,b组合分类) 符合条件的日期(字段c) 
距离现在最近的10个日期 的数据首先想到的是用sql筛选出符合某种条件的所有数据,
这样的事情很简单然后用脚本(python)遍历每一种组合(a,b),然后按日期c倒序排序 取前10

over后的写法:    
   over(order by salary) 按照salary排序进行累计,order by是个默认的开窗函数
   over(partition by deptno)按照部门分区

案例:
with
t_rank as (
        select
            a,
            b,
            c,
            Row_Number() OVER (partition by a,b ORDER BY c desc) rank
        from t_test
    )
 
select a,b,c from t_rank where rank <= 10

额外学习链接:http://www.cnblogs.com/mobiwangyue/p/8328758.html

猜你喜欢

转载自blog.csdn.net/OYY_90/article/details/90166653