Count boolean field values within a single MySQL query?

MySQLMySQLi Database

To count boolean field values within a single query, you can use CASE statement. Let us create a demo table for our example −

mysql> create table countBooleanFieldDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentFirstName varchar(20),
   -> isPassed tinyint(1)
   -> );
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command. 

The query is as follows −

mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Larry',0);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Mike',1);
Query OK, 1 row affected (0.17 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Sam',0);
Query OK, 1 row affected (0.21 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Carol',1);
Query OK, 1 row affected (0.15 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Bob',1);
Query OK, 1 row affected (0.16 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('David',1);
Query OK, 1 row affected (0.13 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Ramit',0);
Query OK, 1 row affected (0.28 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Chris',1);
Query OK, 1 row affected (0.20 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Robert',1);
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement. 

The query is as follows −

mysql> select *from countBooleanFieldDemo;

Here is the output −

+-----------+------------------+----------+
| StudentId | StudentFirstName | isPassed |
+-----------+------------------+----------+
| 1         | Larry            | 0        |
| 2         | Mike             | 1        |
| 3         | Sam              | 0        |
| 4         | Carol            | 1        |
| 5         | Bob              | 1        |
| 6         | David            | 1        |
| 7         | Ramit            | 0        |
| 8         | Chris            | 1        |
| 9         | Robert           | 1        |
+-----------+------------------+----------+
9 rows in set (0.00 sec)

Here is the query to count boolean field values within a single query −

mysql> select sum(isPassed= 1) as `True`, sum(isPassed = 0) as `False`,
   -> (
   -> case when sum(isPassed = 1) > 0 then sum(isPassed = 0) / sum(isPassed = 1)
   -> end
   -> )As TotalPercentage
   -> from countBooleanFieldDemo;

The following is The output −

+------+-------+-----------------+
| True | False | TotalPercentage |
+------+-------+-----------------+
| 6    | 3     | 0.5000          |
+------+-------+-----------------+
1 row in set (0.00 sec)
raja
Published on 01-Apr-2019 07:13:49
Advertisements