I have a table that contains 4 columns and in the 5th column I want to store the count of how many non-null columns there are out of the previous 4. For example:
Where X is any value:
x
Column1 | Column2 | Column3 | Column4 | Count
X | X | NULL | X | 3
NULL | NULL | X | X | 2
NULL | NULL | NULL | NULL | 0
Advertisement
Answer
select
T.Column1,
T.Column2,
T.Column3,
T.Column4,
(
select count(*)
from (values (T.Column1), (T.Column2), (T.Column3), (T.Column4)) as v(col)
where v.col is not null
) as Column5
from Table1 as T