简体   繁体   中英

MySQL counting total number of zeros

I have a table that looks like

| id | day1 | day2 | day3 | day4 | day5 |
| 1  |  4   |  0   |  5   | 0    | 0    |
| 2  |  2   |  0   |  0   | 4    | 1    |

and I want to find to total number of zero entries for each id to give

| id | total_zeros |
| 1  | 3           |
| 2  | 2           |
SELECT id, (day1=0)+(day2=0)+(day3=0)+(day4=0)+(day5=0) total_zeroes
FROM table

Try this one:

select 
id, if(day1=0,1,0)+if(day2=0,1,0)+ if(day3=0,1,0)+if(day4=0,1,0)+if(day5=0,1,0) as total
from test

DEMO HERE

Why do people insist on making such un-usable tables?

You will have to use a case statement, and evaluate each column individually, and then add up the results.

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