Hive中的CONCAT、CONCAT_WS与COLLECT_SET函数

1.CONCAT与CONCAT_WS函数

1.1 CONCAT函数

sql 复制代码
-- concat(str1, str2, ... strN) - returns the concatenation of str1, str2, ... strN or concat(bin1, bin2, ... binN) - returns the concatenation of bytes in binary data  bin1, bin2, ... binN
Returns NULL if any argument is NULL.
Example:
  > SELECT concat('abc', 'def') FROM src LIMIT 1;
  'abcdef'
Function class:org.apache.hadoop.hive.ql.udf.generic.GenericUDFConcat
Function type:BUILTIN

CONCAT(string A/col, string B/col...): 返回输入字符串连接后的结果,支持任意个输入字符串;

1.2 CONCAT_WS函数

sql 复制代码
-- concat_ws(separator, [string | array(string)]+) - returns the concatenation of the strings separated by the separator.
Example:
  > SELECT concat_ws('.', 'www', array('facebook', 'com')) FROM src LIMIT 1;
  'www.facebook.com'
Function class:org.apache.hadoop.hive.ql.udf.generic.GenericUDFConcatWS
Function type:BUILTIN

CONCAT_WS(separator, str1, str2,...): 特殊形式的 CONCAT()。第一个参数为剩余参数间的分隔符。分隔符可以是与剩余参数一样的字符串。如果分隔符是 NULL,返回值也将为 NULL。函数会跳过分隔符参数后的任何 NULL 和空字符串。注意: CONCAT_WS must be "string or array<string>

2.COLLECT_SET函数

2.1 函数语法

sql 复制代码
-- collect_set(x) - Returns a set of objects with duplicate elements eliminated
Function class:org.apache.hadoop.hive.ql.udf.generic.GenericUDAFCollectSet
Function type:BUILTIN

COLLECT_SET(col): 该函数只接受基本数据类型,它的主要作用是将某字段的值进行去重汇总,产生array类型字段。

3.使用案例

3.1 准备数据

name constellation blood_type
小明 白羊座 A
小红 射手座 A
小刚 白羊座 B
小丽 白羊座 A
小虎 射手座 A
小威 白羊座 B

需求:把星座和血型一样的人归类到一起。结果如下:

射手座,A 小红|小虎

白羊座,A 小明|小丽

白羊座,B 小刚|小威

3.2 代码实现

sql 复制代码
SELECT  t1.c_b
       ,CONCAT_WS("|" , collect_set(t1.name))
FROM    (
            SELECT  NAME
                   ,CONCAT_WS(',' , constellation , blood_type) c_b
            FROM    person_info
        ) t1
GROUP BY t1.c_b

4.总结

  • concat 用于连接字符串。
  • concat_ws 用于按照指定的分隔符连接字符串。
  • collect_setgroup byconcat_ws 一起使用可以实现"列转行"。
相关推荐
WhoAmI7 天前
MapReduce框架原理解析一:InputFormat
大数据·hadoop
WhoAmI7 天前
MapReduce框架原理解析三:OutputFormat
大数据·hadoop
WhoAmI7 天前
MapReduce框架原理解析二:Shuffle
大数据·hadoop
王小王-12312 天前
基于 Hive 的网易云音乐数据分析及可视化系统
hive·hadoop·数据分析·音乐数据分析·网易云音乐分析·hive音乐分析·hadoop网易云
极光代码工作室12 天前
基于数据仓库的电商数据分析平台
大数据·hadoop·python·spark·数据可视化
Database_Cool_12 天前
大规模数据分析降本指南:AnalyticDB Serverless 弹性架构实战
数据仓库·阿里云·架构·数据分析·serverless
Database_Cool_12 天前
什么是湖仓一体?和数据仓库的本质区别(附 AnalyticDB MySQL 湖仓一体方案)
数据库·数据仓库·mysql
Chris _data12 天前
WPF 学习第三天 — Modbus RTU 串口通信
hadoop·学习·wpf
知识分享小能手12 天前
Hadoop学习教程,从入门到精通,Flume日志采集系统 — 完整知识点与案例代码(9)
hadoop·学习·flume
递归尽头是星辰12 天前
AI 访问数据仓库:从直连到微服务化
数据仓库·人工智能·微服务·dataagent·ai数据治理