简体   繁体   中英

Count the number of columns populated in a row

I have a table of this style in sql:

id FirstName LastName Age
1 John Williams 25
2 Anne 23

I want to count the number of columns filled in each row, as shown below.

id FirstName LastName Age PopulatedColumns
1 John Williams 25 4
2 Anne 23 3

Does anyone know how to make a script that does this count in sql? But I didn't want to specify the name of the columns, because I have a very large table and it is not practical to put the name of all the columns. Is there a way to do this agnostic? Without putting names?

IN MySQL, you can use arithmetic:

select t.*,
       ( (id is not null) + (firstname is not null) + (lastname is not null) + (age is not null)
       ) as populated_columns
from t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM