I\'m looking for a query which will return me an extra column at the end of my current query which is the count of all columns within the return set which contain a null column.
As in a similar post, SQL is not very suited to work across different columns within a row, but muach better on working across rows.
I'd suggest to turn the table into 'individual' facts about a row, e.g.
select <key>, col1 as value From aTable
UNION
select <key>, col2 as value From aTable
UNION
... and so on for the other columns to be summed.
This can be turned into a view i.e.
create view aView as (select as above).
Then the correct answer is just
select key, count(*)
from aView
where value is null
Group By key
select count(*) - count(ColumnName) as NumberOfNulls from yourTable
returns number of nulls in specific column. if you do this for every column you can get that data.
create table TEST
(
a VARCHAR2(10),
b VARCHAR2(10),
c VARCHAR2(10)
);
insert into TEST (a, b, c)
values ('jas', 'abhi', 'shail');
insert into TEST (a, b, c)
values (null, 'abhi', 'shail');
insert into TEST (a, b, c)
values ('jas', null, 'shail');
insert into TEST (a, b, c)
values ('jas', 'abhi', null);
insert into TEST (a, b, c)
values ('jas', 'abhi', 'abc|xyz');
insert into TEST (a, b, c)
values ('jas', 'abhi', 'abc|xyz');
insert into TEST (a, b, c)
values ('jas', 'abhi', 'abc|xyz');
insert into TEST (a, b, c)
values (null, 'abhi', 'abc|xyz');
commit;
select sum(nvl2(a,null,1)),sum(nvl2(b,null,1)),sum(nvl2(c,null,1)) from test
where a is null
or b is null
or c is null
order by 1,2,3
You can use computed column:
CREATE TABLE testTable(
col1 nchar(10) NULL,
col2 nchar(10) NULL,
col3 AS (case when col1 IS NULL then (1) else (0) end+case when col2 IS NULL then (1) else (0) end)
)
It is not a pretty solution, but should work.
If you are dealing with a big number of columns and many of them you expect to be NULL then you could use sparse columns (available in SQL Server 2008). It will be optimised for NULL and it can automatically generate XML representation for each row of data in the table.
If there isnt a very good reason you need to do this in the SQL, you should just do a for loop through the result set and count the NULL vlues then.
The cost goes from n^n to n..
Oracle has a function NVL2() which makes this easy.
select col1,
col2,
col3,
...
NVL2(col1,0,1)
+NVL2(col2,0,1)
+NVL2(col3,0,1) coln
from whatever