我有一张桌子:
表1
col1 col2 col3 col4
a b (null) c
a b (null) c
a (null) (null) c
(null) b (null) (null)
a b (null) (null)
a b (null) (null)
我表中大约有300列。我需要查找每个非空列的值计数,而无需在表中键入每个列名称。
输出为:
column_name count_of_non_null
col1 5
col2 5
col3 0
col4 3
有办法吗?
答案 0 :(得分:1)
您需要动态PL / SQL来编写条件聚合类型的查询:
select 'col1' col, count(case when col1 is null then 1 end) from table1
union all
select 'col2' col, count(case when col2 is null then 1 end) from table1
因此,您的PL / SQL代码将遵循以下原则
declare
v_cmd varchar2(10000);
begin
for c_column in (select column_name from user_tab_columns where table_name = 'table1') loop
v_counter := v_counter + 1;
v_cmd := v_cmd || 'select ''' || c_column.column_name || ''' col, count(case when ' || c_column.column_name || ' is null then 1 end) from table1 union all ';
end loop;
execute immediate left(v_cmd, length(v_cmd) - 11);
end;
/
我没有测试
答案 1 :(得分:0)
希望您可以使用以下查询来实现。
select col,cnt from (
select col1 col, sum(case when col1 is not null then 1 else 0 end) cnt from tableA group by col1
union all
select col2 col, sum(case when col2 is not null then 1 else 0 end) cnt from tableA group by col2
union all
select col3 col, sum(case when col3 is not null then 1 else 0 end) cnt from tableA group by col3
union all
select col4 col, sum(case when col4 is not null then 1 else 0 end) cnt from tableA group by col4
)