hive group by聚合函数增强

1.grouping sets

grouping sets子句都可以根据UNION连接的多个GROUP BY查询进行逻辑表示

SELECT a,b,SUM(c)FROM tab1 GROUP BY a,b GROUPING SETS((a,b),a,b,())

等价于

SELECT a,b,SUM(c)FROM tab1 GROUP BY a,b
union
SELECT a,null,SUM(c)FROM tab1 GROUP BY a,null
union
SELECT null,b,SUM(c)FROM tab1 GROUP BY null,b
union
SELECT null,null,SUM(c)FROM tab1

2.GROUPING__ID

注意是两个下划线相连,说明聚合结果是属于(grouping sets)哪一个子集的的。

SELECT key, value, GROUPING__ID,count(*)
FROM T1
GROUP BY key, value
GROUPING SETS((key,value),key,value)
;

等价于

SELECT key, value,1,count(*) -- 属于第1个GROUPING SETS子集,即(key,value)
FROM T1
GROUP BY key, value
union 
SELECT key, NULL,2,count(*) -- 属于第2个GROUPING SETS子集,即key
FROM T1
GROUP BY key
union 
SELECT NULL, value,3,count(*) -- 属于第3个GROUPING SETS子集,即value
FROM T1
GROUP BY value


3.WITH CUBE

CUBE是是group by字段的所有组合

GROUP BY a,b,c WITH CUBE

等同于

GROUP BY a,b,c GROUPING SETS((a,b,c),(a,b),(b,c), (a,c),(a),(b),(c),())

4.WITH ROLLUP

ROLLUP子句与GROUP BY一起用于计算维度的层次结构级别的聚合。

GROUP BY a,b,c,WITH ROLLUP

等同于

GROUP BY a,b,c GROUPING SETS((a,b,c),(a,b),(a),())

官网文档

posted @ 2019-02-28 16:50  混沌战神阿瑞斯  阅读(2614)  评论(0编辑  收藏