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
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.
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.
MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With