簡體   English   中英

查詢具有空值的列

[英]Query for retrieving columns with null value

考慮下表

+-----+-----+-----+-----+-----+-----+
|Col01|Col02|Col03|Col04|Col05|Col06|   <===header
+-----+-----+-----+-----+-----+-----+
|data1|data2|NULL |hi   |Hello|Folks|   <===a row
+-----+-----+-----+-----+-----+-----+

現在,我想要一個查詢,該查詢返回列名(在這種情況下為COL03 )或列號作為具有空值的結果。

如何在PostgreSQL中實現呢?

這樣會做嗎?

select case
       when col01 is null
       then 'col1'
       when col02 is null
       then 'col2'
       when col03 is null
       then 'col3'
       when col04 is null
       then 'col4'
       when col05 is null
       then 'col5'
       else null
       end
       which_col
from   tableX

如果您想動態地構建它,我認為您必須執行程序。 您可以通過查詢information_schema.columns來獲取列的名稱。 然后使用該信息創建類似這樣的查詢。

這將返回表中具有空值的每一列的行。

SELECT 'Col1' FROM MyTable WHERE col1 IS NULL
UNION ALL 
SELECT 'Col2' FROM MyTable WHERE col2 IS NULL
UNION ALL 
SELECT 'Col3' FROM MyTable WHERE col3 IS NULL

像這樣:

select 'col1' from Table1 where col1 is null
union all
select 'col2' from Table1 where col2 is null
....
union all
select 'colN' from Table1 where colN is null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM