作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 Hive 1.1.0
有意见,根据条件,它应该返回一个空数组或一个数组 struct<name: string, jobslots: int>
这是我的代码:
select
case when <condition>
then array()
else array(struct(t1.name, t1.jobslots))
end
from table t1;
这里的问题是,空数组
array()
类型为
array<string>
.因此,当我尝试将其插入表中时,它会引发错误。
array<struct<name: string, jobslots:int>>
的空数组以便
Hive's size()
函数在这个数组上返回 0?
最佳答案
你可以使用 collect_list
或 colect_set
用于收集从连接中获取的结构数组,并且连接条件为假,则 collect_list 将生成一个空的结构数组。
此查询返回大小为 0 的数组:
select a.id, size(collect_list(b.str))=0 array_size_zero
from
(select 2 id ) a
left join (select 1 as id, named_struct('name',null,'value',null) as str) b
on a.id=b.id
group by a.id
结果:
a.id array_size_zero
2 true
如果在第一个子查询 a 中更改 id 以与 b 连接,它将返回具有 1 个元素的数组。并且这些结果是相同类型的,您可以使用 union all 轻松检查它。
select a.id, collect_list(b.str) my_array
from
(select 1 id ) a
left join (select 1 as id, named_struct('name',null,'value',null) as str) b
on a.id=b.id
group by a.id
union all
select a.id, collect_list(b.str) my_array
from
(select 2 id ) a
left join (select 1 as id, named_struct('name',null,'value',null) as str) b
on a.id=b.id
group by a.id
结果:
id my_array
1 [{"name":null,"value":null}]
2 []
如果我尝试 UNION ALL 不同类型的空结构数组会发生什么,例如 array():
select 1 id, array() my_array
union all
select a.id, collect_list(b.str) my_array
from
(select 2 id ) a
left join (select 1 as id, named_struct('name',null,'value',null) as str) b
on a.id=b.id
group by a.id
异常(exception):
Error while compiling statement: FAILED: SemanticException Schema ofboth sides of union should match: Column my_array is of typearray on first table and typearray<structname:void,value:void> on second table. Cannot tell theposition of null AST.
select a.id, case when true --Put your condition here instead of dummy <true>
then collect_list(a.str) --not empty
else collect_list(b.str) --this one is empty array of the same type
end as my_array
from
(select 2 id, named_struct('name',null,'value',null) str) a
left join (select 1 as id, named_struct('name',null,'value',null) as str) b
on FALSE
group by a.id
CASE 表达式很高兴并且不会引发关于不兼容类型的异常
关于sql - 如何在 hive 中创建一个空的结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56016700/
我是一名优秀的程序员,十分优秀!