Hive SQL

表生成

  • 行展开
SELECT  uid, shop_id, pid_explode
FROM    (
            SELECT  12345 AS uid,
                    '{"pids": [1, 2, 3], "shop_id": 98765}' AS pid_list
        )
LATERAL VIEW
        json_tuple(pid_list, 'pids', 'shop_id') AS pids, shop_id
LATERAL VIEW
        explode (
            split(
                regexp_replace(substr(pids, 2, length(pids) - 2), '[\\s]+|[\u3000]+', ''),
                '\\,'
            )
        ) AS pid_explode

explode
  • 带pos的行展开
SELECT  uid, shop_id, pid_posexplode, pid_index
FROM    (
            SELECT  12345 AS uid,
                    '{"pids": [1, 2, 3], "shop_id": 98765}' AS pid_list
        )
LATERAL VIEW
        json_tuple(pid_list, 'pids', 'shop_id') AS pids, shop_id
LATERAL VIEW
        posexplode(
            split(
                regexp_replace(substr(pids, 2, length(pids) - 2), '[\\s]+|[\u3000]+', ''),
                '\\,'
            )
        ) AS pid_index, pid_posexplode
posexplode

窗口函数

  • 序列函数
    • row_number:会对所有数值,输出不同的序号,序号唯一且连续,如:1、2、3、4、5。
    • rank:会对相同数值,输出相同的序号,而且下一个序号间断,如:1、1、3、3、5。
    • dense_rank:会对相同数值,输出相同的序号,但下一个序号不间断,如:1、1、2、2、3

排序与分区

  • 相关命令
    • group by
      把相同的key发送到同一个reduce分区中,后面必须做聚合操作
    • distribute by
      把相同的key发送到下游同一个reduce分区中,只是做数据分散,在窗口函数和select中都可以使用
    • sort by
      区内排序,对每个reduce分区内的数据进行排序,不保证全局有序
    • partition by
      对数据进行分区,只能在窗口函数中使用
    • order by
      全部排序,把所有数据拉到同一个节点进行排序,数据量大的时候可能会造成内存溢出
    • cluster by
      如果distribute by和sort by的字段相同时,只用cluster by就可以完成
  • over中partition by和distribute by区别:
    • partition by [key..] order by [key..]只能在窗口函数中使用,而distribute by [key...] sort by [key...]在窗口函数和select中都可以使用。
    • 窗口函数中两者是没有区别的
    • where后面不能用partition by
  • 分组排序取topk
SELECT  *
FROM    (
            SELECT  *,
                    row_number() OVER(
                        PARTITION BY
                                A
                        ORDER BY
                                B DESC
                    ) AS rn
            FROM    table_tmp
        )
WHERE   rn <= topk

参考文档

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容