Sql 如何根据条件获取列名
我有一个检查列是否为null的查询Sql 如何根据条件获取列名,sql,group-by,pivot,presto,unpivot,Sql,Group By,Pivot,Presto,Unpivot,我有一个检查列是否为null的查询 select sum(case when Column_1 is null then 1 else 0 end) as Column_1, sum(case when Column_2 is null then 1 else 0 end) as Column_2, sum(case when Column_3 is null then 1 else 0 end) as Column_3, from TestTable 它给出:
select
sum(case when Column_1 is null then 1 else 0 end) as Column_1,
sum(case when Column_2 is null then 1 else 0 end) as Column_2,
sum(case when Column_3 is null then 1 else 0 end) as Column_3,
from TestTable
它给出:
Column_1 Column_2 Column_3
0 1 0
我想获取具有空值的列名
所以我想要的结果是:
Column_1
Column_3
在普雷斯托我怎么做?从查询返回的输出列名似乎不容易获取。一种方法是:
select (case when count(column_1) <> count(*) then 'Column_1;' else '' end) ||
(case when count(column_2) <> count(*) then 'Column_2;' else '' end) ||
(case when count(column_3) <> count(*) then 'Column_3;' else '' end)
from TestTable ;
选择(计数(列_1)计数(*)时的大小写,然后选择“列_1;”否则结束)||
(count(column_2)count(*)然后'column_2;'else'结束时的大小写)||
(count(column_3)count(*)然后'column_3;'else'结束时的大小写)
从测试表;
一种方法是:
select (case when count(column_1) <> count(*) then 'Column_1;' else '' end) ||
(case when count(column_2) <> count(*) then 'Column_2;' else '' end) ||
(case when count(column_3) <> count(*) then 'Column_3;' else '' end)
from TestTable ;
选择(计数(列_1)计数(*)时的大小写,然后选择“列_1;”否则结束)||
(count(column_2)count(*)然后'column_2;'else'结束时的大小写)||
(count(column_3)count(*)然后'column_3;'else'结束时的大小写)
从测试表;
我知道您希望结果放在单独的行上,而不是放在串联的字符串中
如果是这样,您可以使用unnest()
和数组取消激活现有结果集
select t2.key
from (
select
sum(case when Column_1 is null then 1 else 0 end) as Column_1,
sum(case when Column_2 is null then 1 else 0 end) as Column_2,
sum(case when Column_3 is null then 1 else 0 end) as Column_3
from TestTable
) t1
cross join unnest(
array['Column1', 'Column_2', 'Column_3'],
array[Column1, Column_2, Column_3]
) t2 (key, value)
where t2.value = 0
我知道您希望结果在单独的行上,而不是在串联的字符串中 如果是这样,您可以使用
unnest()
和数组取消激活现有结果集
select t2.key
from (
select
sum(case when Column_1 is null then 1 else 0 end) as Column_1,
sum(case when Column_2 is null then 1 else 0 end) as Column_2,
sum(case when Column_3 is null then 1 else 0 end) as Column_3
from TestTable
) t1
cross join unnest(
array['Column1', 'Column_2', 'Column_3'],
array[Column1, Column_2, Column_3]
) t2 (key, value)
where t2.value = 0
我不确定我是否理解这个问题?计数(第1列)计数(*)?如果桌子空了怎么办?@HaloKu。有趣的问题。然后两个计数都将为
0
,并且该列将(正确地)不被识别为具有NULL
值。thx。在性能方面。如果我有50列。它是否执行50次计数(*)?或者这是所有情况下只需评估一次的东西?@Haloku。没关系<代码>计数(*)不是查询的昂贵部分;读取数据是非常困难的。我希望Presto是只执行一次的数据库之一。我不确定我是否理解这个查询?计数(第1列)计数(*)?如果桌子空了怎么办?@HaloKu。有趣的问题。然后两个计数都将为0
,并且该列将(正确地)不被识别为具有NULL
值。thx。在性能方面。如果我有50列。它是否执行50次计数(*)?或者这是所有情况下只需评估一次的东西?@Haloku。没关系<代码>计数(*)不是查询的昂贵部分;读取数据是非常困难的。我希望Presto会是只执行一次的数据库之一。