Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select row count multiplied by non zero columns? (mysql)

Tags:

sql

php

mysql

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

like image 228
Dalius Avatar asked Dec 14 '25 20:12

Dalius


1 Answers

You just need one aggregate SUM() surrounding all the conditions with no GROUP BY.

SELECT
  SUM(
   (CASE WHEN col1 > 0 THEN 1 ELSE 0 END)
   + (CASE WHEN col2 > 0 THEN 1 ELSE 0 END)
   + (CASE WHEN col3 > 0 THEN 1 ELSE 0 END)
  ) AS total_weight
FROM your_table

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:

SELECT
  SUM(
   (col1 > 0) /* returns 1 or 0 */
    + (col2 > 0)
    + (col3 > 0)
   ) AS total_weight
FROM your_table

http://sqlfiddle.com/#!2/b0d82/2

like image 140
Michael Berkowski Avatar answered Dec 16 '25 09:12

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!