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
How to merge queries in a single MySQL query to get the count of different values in different columns?
Let us first create a table −
mysql> create table DemoTable760 ( ClientId int, ClientId2 int ); Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable760 values(100,200); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable760 values(100,200); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable760 values(300,400); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable760 values(300,400); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable760 values(100,200); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable760 values(100,200); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable760 values(400,500); Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable760;
This will produce the following output -
+----------+-----------+ | ClientId | ClientId2 | +----------+-----------+ | 100 | 200 | | 100 | 200 | | 300 | 400 | | 300 | 400 | | 100 | 200 | | 100 | 200 | | 400 | 500 | +----------+-----------+ 7 rows in set (0.00 sec)
Following is the query to merge queries in a single query to get the count of different values in different columns −
mysql> select sum(ClientId=100) AS ClientId1,sum(ClientId2=200) AS ClientId2 from DemoTable760;
This will produce the following output -
+-----------+-----------+ | ClientId1 | ClientId2 | +-----------+-----------+ | 4 | 4 | +-----------+-----------+ 1 row in set (0.00 sec)
Advertisements
