Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get the count of two table fields in a single MySQL query?
For this, you can use the CASE statement along with SUM(). Here, we will be finding the count of Male and Female records from a column with employee gender values. Let us first create a table −
mysql> create table DemoTable
(
EmployeeGender ENUM('Male','Female')
);
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Male');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Female');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Male');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Female');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Male');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values('Female');
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------------+ | EmployeeGender | +----------------+ | Male | | Female | | Male | | Female | | Male | | Female | +----------------+ 6 rows in set (0.00 sec)
Following is the query to get the count of two table fields in one query −
mysql> select sum(case when EmployeeGender='Male' then 1 else 0 end) as Total_Number_Of_Male_Employee, sum(case when EmployeeGender='Female' then 1 else 0 end) as Total_Number_Of_Female_Employee from DemoTable;
This will produce the following output −
+-------------------------------+---------------------------------+ | Total_Number_Of_Male_Employee | Total_Number_Of_Female_Employee | +-------------------------------+---------------------------------+ | 3 | 3 | +-------------------------------+---------------------------------+ 1 row in set (0.00 sec
Advertisements
