我需要将列值连接成一列。
我在变量中的列名称为 colnames=col1,col2,col3
.
我正在从 unix shell 编写以下查询并调用配置单元。但是当我这样做时,我只得到连接的列名,而不是这些列的值。
select concat('regexp_replace("${colnames}",",","^")) as result from table;
我希望输出为:
ABCD^10^XYZ
(
ABCD
、 10
、 XYZ
是列值)
最佳答案
使用 concat_ws
用 ^
连接值的函数作为分隔符。
常量示例:
hive> select concat_ws('^','ABCD','10', 'XYZ');
OK
ABCD^10^XYZ
shell 变量替换后带有列名的命令应如下所示: select concat_ws('^',col1,col2,col3) as result from table;
在 shell 中,它将如下所示:colnames=col1,col2,col3
hive -e "select concat_ws('^',${colnames}) as result from table"
如果列不是字符串,请使用 shell 将它们转换为字符串,这将允许 concat_ws 处理字符串和非字符串列。例子
colnames=col1,col2,col3
colnames2=$(echo "cast( $colnames as string)" | sed "s/,/ as string), cast( /g")
echo "$colnames2"
输出:cast( col1 as string), cast( col2 as string), cast( col3 as string)
使用新变量传递给 hive,如上例所示。
关于string - 在 hive 中将多列连接成一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51211278/