在Hive中有一个具有以下结构的表:
col1 col2 col3 col4 col5 col6
-----------------------------
AA NM ER NER NER NER
AA NM NER ERR NER NER
AA NM NER NER TER NER
AA NM NER NER NER ERY
写了一个查询来从表中获取记录:
Select distinct(col1),col2, array(concat(
CASE WHEN col3=='ER' THEN 'ER'
WHEN col4=='ERR' THEN 'ERR'
WHEN col5=='TER' THEN 'TER'
WHEN col6=='ERY' THEN 'ERY'
ELSE 'NER' END
但它不起作用。没有得到如何去做。
预期的O / P:
col1 col2 col3
--------------
AA NM ['ER','ERR','TER','ERY']
任何建议/提示都会非常有用。
请尝试以下 -
select col1, col2, array(
max(CASE WHEN col3=='ER' THEN 'ER' else '' end),
max(CASE WHEN col4=='ERR' THEN 'ERR' else '' end),
max(CASE WHEN col5=='TER' THEN 'TER' else '' end),
max(CASE WHEN col6=='ERY' THEN 'ERY' else '' end))
from table
group by col1, col2
您可以使用concat_ws获取看起来像数组的字符串
Select distinct(col1),col2,concat_ws('','[',
concat_ws('', "'",col3,"',", "'",col4,"',","'",col5,"',","'",col6,"'"),
']')
from my_table
这是一个很复杂的问题。我认为简单的解决方案是最简单的解决方案:
select col1, col2, collect_set(col)
from ((select col1, col2, col3 as col from t
) union -- intentional to remove duplicates
(select col1, col2, col4 as col from t
) union -- intentional to remove duplicates
(select col1, col2, col5 as col from t
) union -- intentional to remove duplicates
(select col1, col2, col6 as col from t
)
) t
where col is not null
group by col1, col2;