Query to count how many fields equal to 0 a record has

0

I need to return as many fields as 0 each record has and rank the one with the zeros down. Example:

id   | col2 | col3 | col4
1    | 1    | 0    | 0
2    | 0    | 0    | 0
3    | 0    | 1    | 4
4    | 0    | 3    | 5
5    | 3    | 2    | 40

The return in this case should be:

id  | count(0)
5   | 0
3   | 1
4   | 1
1   | 2
2   | 3
    
asked by anonymous 17.11.2017 / 16:54

1 answer

1

You can use the SUM function and compare each column, if the column is equal to 0 you put 1, otherwise put 0:

(SELECT id, SUM(IF(col2 = 0, 1, 0) + IF(col3 = 0, 1, 0) + IF(col4 = 0, 1, 0)) AS qtde FROM sua_tabela) ORDER BY qtde
    
17.11.2017 / 17:08