简体   繁体   中英

Counting empty or null fields in SQL

I need to count how many empty fields a row contains in an SELECT COUNT(*) statement

My row holds 11 fields and i only need to count in 4 of them. In two of the columns i need to count if they are empty (NOT NULL), and in two i need to count if they hold the value 0

My statement so far:

SELECT COUNT(*) AS subjectcount FROM Tabel WHERE (col1 OR col2) =0 OR (col3 OR col4) = '' AND id=1

Lets say that
col1 = 0
col2 = 1
col3=' '
col4='something'
my sum should then be 2, since two of the fields holds the value im searching for.

MySQL has a neat way of treating booleans as ones or zeroes (for true and false values, respectively) when used in a numeric context. So you could do something like this:

SELECT (col1 = 0) + (col2 = 0) + (col3 = '') + (col4 = '')
FROM   tabel
WHERE 0 in (col1, col2)
  OR '' in (col3, col4)

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