2017-04-10 22 views
0

我試圖執行空檢查。對於e.g:在配置單元中的指定條件下從單行創建多行

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 

什麼是做到這一點的正確方法?

回答

1
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 
+0

非常感謝。我是蜂房新手,請你詳細說明'elt'做了什麼? –

+0

'elt'返回第N個元素的位置('e.pos'從0開始) –

1

一種方法是使用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。這也需要爲每個子查詢單獨掃描。

+0

這不起作用,因爲我們有許多支票和大約1000萬條記錄。 –

+0

@ManishVishnoi。 。 。這將工作,你只需編寫代碼。無論如何,它只能回答你所問的問題。你問了2列和一種支票。如果您還有其他問題,請將其作爲另一個問題。 –