Getting count of two different sets of rows in a table and then dividing them in MySQL



For this, use count(*) and the divide the count of two different sets of rows. Let us first create a table −

mysql> create table DemoTable(isMarried tinyint(1));
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.22 sec)
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.07 sec)
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+
| isMarried |
+-----------+
| 1         |
| 0         |
| 1         |
| 1         |
| 1         |
+-----------+
5 rows in set (0.00 sec)

Following is the query to get the count of two different sets of rows in a table and then dividing them −

mysql> select
   (
      select count(*) from DemoTable where isMarried=1) /
   (
      select count(*) from DemoTable where isMarried=0
   ) AS divide from dual;

This will produce the following output −

+--------+
| divide |
+--------+
| 4.0000 |
+--------+
1 row in set (0.00 sec)

Advertisements