SQL Hive - 用 0 替换空值 (Hadoop Hive)
SQL Hive - Replace null values with 0 (Hadoop Hive)
进行左连接后,我留下了许多 null(空)值。如何仅在同一查询的某些列中将这些空值替换为 0?
select
m1.*, t2.Apple, t3.Berry, t4.Cherry
from
table1 as t1
left join table2 as t2 on t1.id = t2.id
left join table3 as t3 on t1.id = t3.id
left join table3 as t4 on t1.id = t4.id
;
示例输出
ID Apple Berry Cheery
1 1 NULL 1
2 1 NULL NULL
3 NULL 1 NULL
4 NULL NULL NULL
您可以使用 coalesce()
将 null
值替换为 0
s:
select
t1.*,
coalesce(t2.Apple, 0) as apple,
coalesce(t3.Berry, 0) as berry,
coalesce(t4.Cherry, 0) as cherry
from
table1 as t1
left join table2 as t2 on t1.id = t2.id
left join table3 as t3 on t1.id = t3.id
left join table4 as t4 on t1.id = t4.id
;
请注意,这假设所有 3 个水果列都是数字数据类型。
旁注:我修正了您原始查询中 table 别名的一些拼写错误。
进行左连接后,我留下了许多 null(空)值。如何仅在同一查询的某些列中将这些空值替换为 0?
select
m1.*, t2.Apple, t3.Berry, t4.Cherry
from
table1 as t1
left join table2 as t2 on t1.id = t2.id
left join table3 as t3 on t1.id = t3.id
left join table3 as t4 on t1.id = t4.id
;
示例输出
ID Apple Berry Cheery
1 1 NULL 1
2 1 NULL NULL
3 NULL 1 NULL
4 NULL NULL NULL
您可以使用 coalesce()
将 null
值替换为 0
s:
select
t1.*,
coalesce(t2.Apple, 0) as apple,
coalesce(t3.Berry, 0) as berry,
coalesce(t4.Cherry, 0) as cherry
from
table1 as t1
left join table2 as t2 on t1.id = t2.id
left join table3 as t3 on t1.id = t3.id
left join table4 as t4 on t1.id = t4.id
;
请注意,这假设所有 3 个水果列都是数字数据类型。
旁注:我修正了您原始查询中 table 别名的一些拼写错误。