One way to do this is to reveal the data and then group it again. This gives you the option to use count(distinct) :
select name, count(distinct val) from t unpivot (val for col in (FieldA, FieldB, FieldC, FieldD)) unpvt group by name;
However, the most efficient way to do this is to keep all processing in one line - no join or group by or union s. Assuming none of the values ββis NULL , the following holds for the four columns:
select name, 4 - ((case when FieldA in (FieldB, FieldC, FieldD) then 1 else 0 end) + (case when FieldB in (FieldC, FieldD) then 1 else 0 end) + (case when FieldC in (FieldD) then 1 else 0 end) ) from t;
That is, start with the total number of columns. Then subtract 1 each time a column looks like a column that comes later. This last condition ensures that duplicates are not counted more than once.
source share