IN MYSQL HOW TO COUNT NON-EMPTY CELLS IN ONE ROW

Suppose we want to count the non empty cells in table 'your_table_name' .
The columns that we want to select for non empty criterion are 'column1', 'column2', 'column3'.
Here is the query for the same.

SELECT id,col1+col2+col3 AS COUNT
FROM
(
SELECT id, /*now onwards are columns that we want to select*/
CASE column1 WHEN column1<>'' THEN '1' ELSE '0' END AS col1,
CASE column2 WHEN column2<>'' THEN '1' ELSE '0' END AS col2,
CASE column3 WHEN column3<>'' THEN '1' ELSE '0' END AS col3,
FROM your_table_name GROUP BY id
)
AS subtable;

This query will return the recordset having two columns named as id and COUNT in which COUNT will contain the no. of non empty cells for respective id.

1 comments:

Editor said...

thanks this one is also a different solution