Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count boolean field values within a single query

Tags:

sql

mysql

I like to get the amount of rows where a certain field is either 1 or 0.

My table looks like this:

ID | name | my_bool
===================
 1 | foo  | 1
 2 | bar  | 1
 3 | loo  | 0
 4 | zoo  | 1

as result I expect

YES | NO  | percentage
======================
 3  | 1   | 0.3333

YES is how many rows where my_bool is true (1) while NO is where rows with false (0)

percentage give the percentage of YES to NO

like image 913
Xaver Avatar asked Mar 16 '14 16:03

Xaver


People also ask

How get Boolean value in SQL query?

SQL Server Boolean A BIT data type is used to store bit values from 1 to 64. So, a BIT field can be used for booleans, providing 1 for TRUE and 0 for FALSE. CREATE TABLE testbool ( sometext VARCHAR(10), is_checked BIT ); This means you can insert either a 1 (for TRUE) or 0 (for FALSE) into this column.

How do I count rows in SQL with conditions?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

What is count (*) in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.

Can we use count in where clause in MySQL?

SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.


1 Answers

In MySQL, you can do this easily with conditional aggregation:

select sum(my_bool = 1) as yes, sum(my_bool = 0) as no
from table t;

EDIT:

The percentage is very easy:

select sum(my_bool = 1) as yes, sum(my_bool = 0) as no, avg(my_bool = 0)
from table t;

However, your value suggests you are looking for a ratio, not a percentage. For that, you need to be careful about divide by zero:

select sum(my_bool = 1) as yes, sum(my_bool = 0) as no,
       (case when sum(my_bool = 1) > 0 then sum(my_bool = 0) / sum(my_bool = 1)
        end)
from table t;
like image 182
Gordon Linoff Avatar answered Sep 19 '22 14:09

Gordon Linoff