sql—在配置单元中的指定条件下从单行创建多行

vngu2lb8  于 2021-05-29  发布在  Hadoop
关注(0)|答案(2)|浏览(332)

我正在尝试实现空检查。例如:

Col_A | Col_B | Col_C | Col_D
null  | boy   | null  | dust

然后我希望输出为:

Col_A | Col_B | Col_C | Col_D | New_Col
null  | boy   | null  | dust  | Col_A failed null check
null  | boy   | null  | dust  | Col_D failed null check

正确的方法是什么?

laximzn5

laximzn51#

select t.*
      ,concat(elt(e.pos+1,'Col_A','Col_B','Col_C','Col_D'),' failed null check') as New_Col
from   mytable t lateral view posexplode (array(Col_A,Col_B,Col_C,Col_D)) e
where  e.val is null
db2dz4w8

db2dz4w82#

一种方法使用 union all :

select Col_A, Col_B, Col_C, Col_D, 'Col_A failed NULL check' as new_col
from t
where Col_A is null
union all
select Col_A, Col_B, Col_C, Col_D, 'Col_B failed NULL check' as new_col
from t
where Col_B is null
union all
select Col_A, Col_B, Col_C, Col_D, 'Col_C failed NULL check' as new_col
from t
where Col_C is null
union all
select Col_A, Col_B, Col_C, Col_D, 'Col_D failed NULL check' as new_col
from t
where Col_D is null;

这是相当残忍的武力。如果有很多列,可以使用电子表格生成sql。这还需要对每个子查询进行单独的扫描。

相关问题