首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将代码字符串转换为单元中的desc

将代码字符串转换为单元中的desc
EN

Stack Overflow用户
提问于 2018-07-28 00:08:42
回答 1查看 356关注 0票数 3

这里我们有一个连字符字符串,像0-1-3..。而且长度不是固定的,我们在单元中也有一个明细表来解释每个代码的含义。

DETAIL | code | desc | + ---- + ---- + | 0 | AAA | | 1 | BBB | | 2 | CCC | | 3 | DDD |

现在,我们需要一个单元查询来将代码字符串转换为描述字符串。

例如: case 0-1-3应该得到一个类似于AAA-BBB-DDD的字符串。

对如何得到它有什么建议?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-28 09:40:16

Split您的字符串以获得数组、explode数组和使用详细表连接(在我的示例中使用CTE代替它,使用普通表)以使desc与代码连接。然后使用collect_list(desc)组装字符串以获得数组+ concat_ws()以获得连接字符串:

代码语言:javascript
复制
select concat_ws('-',collect_list(d.desc)) as code_desc 
from
( --initial string explode
select explode(split('0-1-3','-')) as code
) s
inner join 
(-- use your table instead of this subquery
select 0  code, 'AAA' desc union all
select 1, 'BBB' desc union all
select 2, 'CCC' desc union all
select 3, 'DDD' desc
) d on s.code=d.code;

结果:

代码语言:javascript
复制
OK
AAA-BBB-DDD
Time taken: 114.798 seconds, Fetched: 1 row(s)

如果需要保留原始顺序,则使用posexplode返回元素及其在原始数组中的位置。然后,您可以在collect_list()之前通过记录ID和pos进行排序。

如果您的字符串是表列,则使用横向视图选择爆炸性值。

这是一个更复杂的例子,顺序保持和横向视图。

代码语言:javascript
复制
select str as original_string, concat_ws('-',collect_list(s.desc)) as transformed_string
from
(
select s.str, s.pos, d.desc     
from
( --initial string explode with ordering by str and pos
  --(better use your table PK, like ID instead of str for ordering), pos
select str, pos, code from ( --use your table instead of this subquery
                             select '0-1-3' as str union all
                             select '2-1-3' as str union all
                             select '3-2-1' as str
                           )s
lateral view outer posexplode(split(s.str,'-')) v as pos,code
) s
inner join 
(-- use your table instead of this subquery
select 0  code, 'AAA' desc union all
select 1, 'BBB' desc union all
select 2, 'CCC' desc union all
select 3, 'DDD' desc
) d on s.code=d.code
distribute by s.str -- this should be record PK candidate
sort by s.str, s.pos --sort on each reducer
)s
group by str;

结果:

代码语言:javascript
复制
OK
0-1-3   AAA-BBB-DDD
2-1-3   CCC-BBB-DDD
3-2-1   DDD-CCC-BBB
Time taken: 67.534 seconds, Fetched: 3 row(s)

请注意,使用的是distribute + sort,而不是简单的order by str, pos。分布式+排序工作在完全分布式模式下,order by也将工作正确,但在单一减速器上。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51566924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档