我有一张像
这样的表格我希望输出像这样(group将结果连接到一个记录中,group_concat应该按值DESC对结果进行排序)。
这是我试过的查询,
SELECT id,
CONCAT('{',CONCAT_WS(',',GROUP_CONCAT(CONCAT('"',key, '":"',value, '"'))), '}') AS value
FROM
table_name
GROUP BY id
我希望目标表中的值应按源表值排序(降序)。
为此,我尝试了 GROUP_CONCAT(... ORDER BY值)。
看起来Hive不支持此功能。有什么其他方法可以在蜂巢中实现这一目标吗?
答案 0 :(得分:2)
试试这个查询。
Hive不支持GROUP_CONCAT函数,但您可以使用collect_list函数来实现类似的功能。此外,您将需要使用分析窗口函数,因为Hive不支持collect_list函数内的ORDER BY子句
select
id,
-- since we have a duplicate group_concat values against the same key
-- we can pick any one value by using the min() function
-- and grouping by the key 'id'
-- Finally, we can use the concat and concat_ws functions to
-- add the commas and the open/close braces for the json object
concat('{', concat_ws(',', min(g)), '}')
from
(
select
s.id,
-- The window function collect_list is run against each row with
-- the partition key of 'id'. This will create a value which is
-- similar to the value obtained for group_concat, but this
-- same/duplicate value will be appended for each row for the
-- same key 'id'
collect_list(s.c) over (partition by s.id
order by s.v desc
rows between unbounded preceding and unbounded following) g
from
(
-- First, form the key/value pairs from the original table.
-- Also, bring along the value column 'v', so that we can use
-- it further for ordering
select
id,
v,
concat('"', k, '":"', v, '"') as c
from
table_name -- This it th
)
s
)
gs
-- Need to group by 'id' since we have duplicate collect_list values
group by
id