In addition to the above, a potential approach would be to use the functionality of PIVOT and UNPIVOT .
First create a table and paste the data into the question:
CREATE TABLE so_40957006 ( [name] VARCHAR(24), [col1] VARCHAR(24), [col2] VARCHAR(24), [col3] VARCHAR(24), [col4] VARCHAR(24) ) INSERT INTO so_40957006 VALUES('abc', null, ' a@c.com ', null, null) INSERT INTO so_40957006 VALUES('bbc', null, null, null, null)
First, we will create an identification table so that we can uniquely identify each row of data and insert data.
CREATE TABLE so_40957006_id ( [lid] INT IDENTITY(1, 1), [name] VARCHAR(24), [col1] VARCHAR(24), [col2] VARCHAR(24), [col3] VARCHAR(24), [col4] VARCHAR(24) ) INSERT INTO so_40957006_id SELECT ISNULL([name], 1) AS [name] ,ISNULL([col1], 1) AS [col1] ,ISNULL([col2], 1) AS [col2] ,ISNULL([col3], 1) AS [col3] ,ISNULL([col4], 1) AS [col4] FROM so_40957006
Note that in the process, we converted any of the columns that have a null value of 1 using IsNull . Now the table is as follows.
lid name col1 col2 col3 col4 1 abc 1 a@c.com 1 1 2 bbc 1 1 1 1
In doing so, we can now use PIVOT and UNPIVOT to verticalize data. For example, by running the query below
SELECT [lid], [cols], [val] FROM (SELECT [lid], [name], [col1], [col2], [col3], [col4] FROM so_40957006_id) p UNPIVOT (val FOR cols IN ([name], [col1], [col2], [col3], [col4]) ) AS unpvt
provides you with vertical output:
lid cols val 1 name abc 1 col1 1 1 col2 a@c.com 1 col3 1 1 col4 1 2 name bbc 2 col1 1 2 col2 1 2 col3 1 2 col4 1
Since the values ββyou want to count (i.e. NULL s) are 1, you can simply run the GROUP BY + SUM statement:
SELECT [lid], SUM(cast([val] as integer)) as CountNulls FROM ( SELECT [lid], [cols], [val] FROM (SELECT [lid], [name], [col1], [col2], [col3], [col4] FROM so_40957006_id) p UNPIVOT (val FOR cols IN ([name], [col1], [col2], [col3], [col4]) ) AS unpvt ) a WHERE ISNUMERIC([val]) = 1 GROUP BY [lid]
with exit
lid CountNulls 1 3 2 4
With [lid] you can JOIN return this result to the original table to generate your result set.