处理impala中的空数据

mccptt67  于 2021-06-26  发布在  Hive
关注(0)|答案(3)|浏览(1483)

我在努力理解 Impala 的算术运算行为
我使用下表

╔════╦══════════════╦══════════╗
║ id ║  name        ║ salary   ║
╠════╬══════════════╬══════════╣
║  1 ║  cde         ║ 5636     ║
║  2 ║  asd         ║  148     ║
║  3 ║  pwe         ║  null    ║
║  4 ║  lmn         ║  959     ║
╚════╩══════════════╩══════════╝

当我执行以下查询时

select salary+20 as sum1 from table where id=3;

它还给了我

|sum1
  ---|-----
   1 |NULL

当我在列上运行sum时

select sum(salary) as sum1 from table;

     |sum1
  ---|-----
   1 |6743

我无法理解相同的算术运算是如何表现不同的

iyr7buue

iyr7buue1#

这些是不同的算术查询。
在第一个查询中,您希望db返回 salary+20 从第三排开始。好吧 salary 第3行的 NULL . 所以db会看到的 NULL+20=NULL 然后回来 NULL .
但是在第二个查询中: sum(salary) from table; 要求db对整个 salary 列并返回给您。所以它看着它,确实 5636+148+959=6743 (忽略) NULL ).
总之,在第一个查询中,您正在执行一个基本的算术运算符。但是第二个问题 sum() 是应用于返回行的运算符。作为更好的测试,试着跑步 select sum(salary) as sum1 from table where id=3 看看你得到了什么,以便更好地了解正在发生的事情。

omjgkv6w

omjgkv6w2#

你有没有试过这样的方法:

select sum(COALESCE(salary,0)) as sum1 from table;

这应该确保返回的值是一个数字。类似于leftjoin的答案。您还可以使用case语句或where语句来实现这一点。
资料来源:
https://www.cloudera.com/documentation/enterprise/5-4-x/topics/impala_conditional_functions.html

ogq8wdun

ogq8wdun3#

null不是零(0),零也不是null,它是一个值,这是最重要的。null表示缺少值,nothing。 sum() 仅聚合值。如果数据集中没有任何值,则返回null。如果是一些值,sum()将聚合它们,忽略空值。如果你想转换 NULL 它归零,使用 NVL() 功能:

select nvl(sum(salary),0) as sum1 from table where ...

如果数据集中没有值,此查询将返回0。

相关问题