Here is my table structure
id col1 col2 col3 col4 1 1 1 2 1
the thing is, i want to SUM field (col1,col2,col3,col4) but only the value 1. so based on the record above. the result would be 3 (col1+col2+col4), becauser value from col3 is 2 not 1.
sorry for bad grammar.
Advertisement
Answer
Either you mean:
- You want to calculate a new column on each row which is the sum of columns 1 through 4 if those columns are 1 (which is the same as the count of columns which are 1), or
- You want to calculate the sum of those columns but only when the row values of those columns are 1
For 1:
SELECT id, col1, col2, col3, col4 , CASE WHEN col1 = 1 THEN 1 ELSE 0 END + CASE WHEN col2 = 1 THEN 1 ELSE 0 END + CASE WHEN col3 = 1 THEN 1 ELSE 0 END + CASE WHEN col4 = 1 THEN 1 ELSE 0 END AS row_count_of_ones FROM table_name;
For 2:
SELECT SUM( CASE WHEN col1 = 1 THEN 1 ELSE 0 END + CASE WHEN col2 = 1 THEN 1 ELSE 0 END + CASE WHEN col3 = 1 THEN 1 ELSE 0 END + CASE WHEN col4 = 1 THEN 1 ELSE 0 END ) AS count_of_ones FROM table_name;