For this, you can use the aggregate function SUM(). Let us first create a table −
mysql> create table DemoTable ( isMarried tinyint(1) ); Query OK, 0 rows affected (0.84 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable values(1); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(1); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(1); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(1); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+ | isMarried | +-----------+ | 0 | | 1 | | 1 | | 0 | | 1 | | 1 | | 0 | +-----------+ 7 rows in set (0.00 sec)
Following is the query to count the number of 0s and 1s from one column and display them in two columns −
mysql> select sum(tbl.isMarried=1) as all_one_count, sum(tbl.isMarried=0) as all_zero_count, sum(tbl.isMarried in(0,1)) as all_zero_count_and_one_count from DemoTable tbl;
This will produce the following output −
+---------------+----------------+------------------------------+ | all_one_count | all_zero_count | all_zero_count_and_one_count | +---------------+----------------+------------------------------+ | 4 | 3 | 7 | +---------------+----------------+------------------------------+ 1 row in set (0.04 sec)