Suppose I have a table:
col1, col2, col3
1 0 1.3
0 0 0
0 1 0
1 1.5 1
Now, let’s say each row has a “weight” calculated as this:
(col1 > 0 ? 1 : 0) + (col2 > 0 ? 1 : 0) + (col3 > 0 ? 1 : 0)
How can I select the total weight of all rows?
With the data I have given the total weight is 2+0+1+3=6
You just need one aggregate
SUM()surrounding all the conditions with noGROUP BY.http://sqlfiddle.com/#!2/b0d82/1
I am using
CASE WHEN...here as it is portable across any RDBMS. Since MySQL will return a boolean 0 or 1 for the conditions though, it can be simplified in MySQL as:http://sqlfiddle.com/#!2/b0d82/2