declare @T table
(
Col1 int,
Col2 int,
Col3 int,
Col4 int
)
insert into @T values
(1, 0 , null, null),
(0, null, 0 , 1)
select U.ColName
from
(
select count(nullif(Col1, 0)) as Col1,
count(nullif(Col2, 0)) as Col2,
count(nullif(Col3, 0)) as Col3,
count(nullif(Col4, 0)) as Col4
from @T
) as T
unpivot
(C for ColName in (Col1, Col2, Col3, Col4)) as U
where U.C = 0
Wynik:
ColName
----------
Col2
Col3
Ideą tego jest liczenie nie null wartości i zachowaj tylko te z liczbą 0 .
LICZBA
zlicza tylko wartości inne niż null.
NULLIF(ColX, 0)
utworzy wszystkie 0 na null .
Wewnętrzne zapytanie zwraca jeden wiersz z czterema kolumnami. UNPIVOT
odwróci to tak, że masz dwie kolumny i cztery wiersze.
Na koniec where U.C = 0 upewnia się, że otrzymujesz tylko kolumny, które nie mają wartości innych niż null lub 0 .