В MySQL логические выражения можно рассматривать как числа, с «1» для true и «0» для false.
Итак, это делает то, что вы хотите:
select ((col1 is not null) + (col2 is not null) + (col3 is not null) +
(col4 is not null) + (col5 is not null)
) as num_not_null,
((col1 is null) + (col2 is null) + (col3 is null) +
(col4 is null) + (col5 is null)
) as num_null
from t;
Обратите внимание, что это интерпретирует «пробел» как NULL
.Вы также можете легко использовать <> ''
или аналогичную логику, если «пробел» означает что-то еще.
РЕДАКТИРОВАТЬ:
Для других значений вам необходимо расширить логику.Простой способ:
select ((col1 is not null and col1 not in ('0', '')) +
(col2 is not null and col2 not in ('0', '')) +
(col3 is not null and col3 not in ('0', '')) +
(col4 is not null and col4 not in ('0', '')) +
(col5 is not null and col5 not in ('0', ''))
) as num_not_null,
((col1 is null or col1 in ('0', '')) +
(col2 is null or col2 in ('0', '')) +
(col3 is null or col3 in ('0', '')) +
(col4 is null or col4 in ('0', '')) +
(col5 is null or col5 in ('0', ''))
) as num_null
from t;