I am working with an Oracle db, trying to count non-null values in columns and report results by row types. Please help, I'm regularly humbled by the power of SQL.
I have a table of financial-reporting-form data: column 1 is the form type, columns 2..900 (seriously it's quite wide) have a null or a number. So I'm trying to characterize by form type the non-null values.
Sample fragment of table t1 - only shows 2 but there are 8 form types:
ftype c1 c2 c3 c4 c5
----- -- -- -- -- --
a 1 2 3 null null
b null null null 4 5
b null null null 44 55
The desired report is below; the numbers are the non-null counts from the sample table above:
a b
-- --
c1 1 0
c2 1 0
c3 1 0
c4 0 2
c5 0 2
With this report we'll be able to say "Hey, column 4 is never populated for Form A".
If I went at the problem in a procedural programming language I'd write something like the following. Then I'd emit the results as a big table:
for FORM in FormA .. FormH
for COLUMN in Col1 .. Col900
select count(*) from t1 where ftype = '${FORM}' and ${COLUMN} is not null;
end for
end for
These posts at SO pointed me to the CASE construct but are not quite the same:
Count number of NULL values in each column in SQL
Counting non-null columns in a rather strange way
I also created a SQL Fiddle for this question: http://sqlfiddle.com/#!2/e4d43/2
What's the smart way? Do I have to write a huge number of SQL queries? Thanks in advance.
Update 1: Thanks for the quick replies. I just need the information, don't care if the report has the columns across and the types down, does it the solution much easier (i.e., no pivot required)? The following would be just fine by me, it would get very very wide but we'll cope:
c1 c2 c3 c4 c5
-- -- -- -- --
a 1 1 1 0 0
b 0 0 0 2 2