hive grouping sets 和 cube 用法

本文介绍了GroupingSets和Cube的基本概念及应用场景,对比了GroupingSets与LateralViewExplode的方法,并探讨了Cube在使用过程中遇到的问题及其解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • grouping sets 和cube基本知识。

    基础知识可参考 http://blog.youkuaiyun.com/mashroomxl/article/details/22578471

    grouping sets 适用于多维度统计,可以代替之前lateral view explode 方式

    cube 相当于grouping sets 所有条件组合。

    平时跑临时需求看数据,也可以用cube。比如看某款游戏android,ios,_NONE的数量,很方便可以用一个sql写。

  • grouping sets 与lateral view explode方式比较

    结论:map和reducer数一样,在运算速度上差距也不大,但写法会比较简单。

  • cube 使用碰到的情况

    当>=5个维度且聚合中用了distinct,会报如下错误

    An additional MR job is introduced since the cardinality of grouping sets is more than hive.new.job.grouping.set.cardinality.
    This functionality is not supported with distincts.
    Either set hive.new.job.grouping.set.cardinality to a high number (higher than the number of rows per input row due to grouping sets in the query),
    or rewrite the query to not use distincts. The number of rows per input row due to grouping sets is 32 (state=42000,code=10226)

    解决方法:如错误日志描述给出的解决方法,可以通过修改 hive.new.job.grouping.set.cardinality 配置,或者在聚合中不用distinct来解决。

    目前我们采用后者这个方式,可以通过在子查询中用group by去重,避免在聚合中用到distinct。

### 使用 Hive 中 `GROUPING SETS` 的方法 #### 示例与语法解释 在 Hive SQL 查询中,`GROUPING SETS` 提供了一种简洁的方式来执行多维分组聚合。这使得可以在单个查询中指定多个不同的组合来进行数据汇总。 创建表并插入测试数据: ```sql CREATE TABLE IF NOT EXISTS student_scores ( class STRING, sex STRING, course STRING, score INT ); INSERT INTO student_scores VALUES ('ClassA', 'Male', 'Math', 80), ('ClassB', 'Female', 'English', 90), ('ClassA', 'Female', 'Math', 75); ``` 使用 `GROUPING SETS` 执行复杂分组操作: ```sql SELECT GROUPING__ID, -- 特殊列用于区分不同层次的分组结果 class, sex, course, AVG(score) AS average_score FROM student_scores GROUP BY class, sex, course WITH ROLLUP; -- 或者使用 CUBE 替代 ROLLUP 来获取更全面的结果集 ``` 上述例子展示了如何利用 `WITH ROLLUP` 关键字来简化某些类型的 `GROUPING SETS` 定义[^1]。对于更加复杂的场景,则可以直接定义具体的分组集合: ```sql SELECT GROUPING__ID, class, sex, course, AVG(score) AS average_score FROM student_scores GROUP BY class, sex, course GROUPING SETS( (class, course), (class, sex), (sex, course), () -- 表示全局总计行 ); ``` 此查询会返回四类不同的分组统计信息:按班级课程、按性别课程、仅限于特定科目以及整个表格的整体平均成绩[^3]。 注意,在输出结果集中有一个名为 `GROUPING__ID` 的特殊字段,它用来指示当前记录对应的是哪种级别的分组情况。通过检查该值可以帮助理解每一行代表的数据范围[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值