Hive GROUPING SETS和GROUPING__IDCUBEROLLUP
Posted 二十六画生的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hive GROUPING SETS和GROUPING__IDCUBEROLLUP相关的知识,希望对你有一定的参考价值。
Hive支持以下3种运算。
grouping sets(a,b,(a,b))统计列包含:(a)、(b)、(a,b)
rollup(a,b,c)统计列包含:(a,b,c)、(a,b)、(a)、()
cube(a,b,c) 统计列包含:(a,b,c)、(a,b)、(a,c)、(b,c)、(a)、(b)、(c)、()
GROUPING SETS和GROUPING__ID
说明
在一个GROUP BY查询中,根据不同的维度组合进行聚合,等价于将不同维度的GROUP BY结果集进行UNION ALL
GROUPING__ID,表示结果属于哪一个分组集合。
查询语句:
1 2 3 4 5 6 7 8 9 | select month , day , count ( distinct cookieid) as uv, GROUPING__ID from cookie.cookie5 group by month , day grouping sets ( month , day ) order by GROUPING__ID; |
等价于:
1 2 3 | SELECT month , NULL , COUNT ( DISTINCT cookieid) AS uv,1 AS GROUPING__ID FROM cookie5 GROUP BY month UNION ALL SELECT NULL , day , COUNT ( DISTINCT cookieid) AS uv,2 AS GROUPING__ID FROM cookie5 GROUP BY day |
查询结果
结果说明
第一列是按照month进行分组
第二列是按照day进行分组
第三列是按照month或day分组是,统计这一组有几个不同的cookieid
第四列grouping_id表示这一组结果属于哪个分组集合,根据grouping sets中的分组条件month,day,1是代表month,2是代表day
再比如:
1 2 3 4 5 6 7 | SELECT month , day , COUNT ( DISTINCT cookieid) AS uv, GROUPING__ID FROM cookie5 GROUP BY month , day GROUPING SETS ( month , day ,( month , day )) ORDER BY GROUPING__ID; |
等价于:
1 2 3 4 5 | SELECT month , NULL , COUNT ( DISTINCT cookieid) AS uv,1 AS GROUPING__ID FROM cookie5 GROUP BY month UNION ALL SELECT NULL , day , COUNT ( DISTINCT cookieid) AS uv,2 AS GROUPING__ID FROM cookie5 GROUP BY day UNION ALL SELECT month , day , COUNT ( DISTINCT cookieid) AS uv,3 AS GROUPING__ID FROM cookie5 GROUP BY month , day |
CUBE
说明
根据GROUP BY的维度的所有组合进行聚合
查询语句
1 2 3 4 5 6 7 | SELECT month , day , COUNT ( DISTINCT cookieid) AS uv, GROUPING__ID FROM cookie5 GROUP BY month , day WITH CUBE ORDER BY GROUPING__ID; |
等价于
1 2 3 4 5 6 7 | SELECT NULL , NULL , COUNT ( DISTINCT cookieid) AS uv,0 AS GROUPING__ID FROM cookie5 UNION ALL SELECT month , NULL , COUNT ( DISTINCT cookieid) AS uv,1 AS GROUPING__ID FROM cookie5 GROUP BY month UNION ALL SELECT NULL , day , COUNT ( DISTINCT cookieid) AS uv,2 AS GROUPING__ID FROM cookie5 GROUP BY day UNION ALL SELECT month , day , COUNT ( DISTINCT cookieid) AS uv,3 AS GROUPING__ID FROM cookie5 GROUP BY month , day |
查询结果
ROLLUP
说明
是CUBE的子集,以最左侧的维度为主,从该维度进行层级聚合
查询语句
-- 比如,以month维度进行层级聚合
1 2 3 | SELECT month , day , COUNT ( DISTINCT cookieid) AS uv, GROUPING__ID FROM cookie5 GROUP BY month , day WITH ROLLUP ORDER BY GROUPING__ID; |
可以实现这样的上钻过程:
月天的UV->月的UV->总UV
--把month和day调换顺序,则以day维度进行层级聚合:
可以实现这样的上钻过程:
天月的UV->天的UV->总UV
(这里,根据天和月进行聚合,和根据天聚合结果一样,因为有父子关系,如果是其他维度组合的话,就会不一样)
以上是关于Hive GROUPING SETS和GROUPING__IDCUBEROLLUP的主要内容,如果未能解决你的问题,请参考以下文章
hive grouping sets 实现原理
Hive 如何使用 Grouping Sets
Hive 如何使用 Grouping Sets
hive grouping sets 等聚合函数
大数据之hive:hive新功能之GROUPING SETS,Cube, Rollup
Hive之grouping sets用法详解