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 一起使用可以实现"列转行"。
相关推荐
钊兵1 小时前
hivesql是什么数据库?
大数据·hive
RestCloud2 小时前
产品更新丨谷云科技 iPaaS 集成平台 V7.5 版本发布
数据仓库·系统安全·api·数字化转型·ipaas·数据集成平台·集成平台
RestCloud2 小时前
数据清洗(ETL/ELT)原理与工具选择指南:企业数字化转型的核心引擎
数据仓库·数据安全·etl·数据集成·elt·集成平台
wingaso4 小时前
[经验总结]删除gitlab仓库分支报错:错误:无法推送一些引用到“http:”
linux·数据仓库·git
线条17 小时前
MapReduce Shuffle 全解析:从 Map 端到 Reduce 端的核心数据流
大数据·hadoop·mapreduce
火龙谷1 天前
【hadoop】Kafka 安装部署
大数据·hadoop·kafka
火龙谷1 天前
【hadoop】Flume的相关介绍
大数据·hadoop·flume
RestCloud1 天前
企业对数据集成工具的需求及 ETL 工具工作原理详解
数据仓库·系统安全·etl·数字化转型·数据集成平台·集成平台
薇晶晶1 天前
spark基本介绍
hadoop
IvanCodes1 天前
九、HQL DQL七大查询子句
大数据·数据库·hive