- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get multiple count in a single MySQL query for specific column values
For this, you can use aggregate function sum() along with parameter value for specific column. Let us first create a table −
mysql> create table DemoTable1790 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(20), Score int ); Query OK, 0 rows affected (0.94 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1790(Name,Score) values('Chris',45); Query OK, 1 row affected (0.38 sec) mysql> insert into DemoTable1790(Name,Score) values('David',55); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1790(Name,Score) values('David',98); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1790(Name,Score) values('Chris',91); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1790(Name,Score) values('Mike',99); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1790(Name,Score) values('Carol',55); Query OK, 1 row affected (0.35 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1790;
This will produce the following output −
+----+-------+-------+ | Id | Name | Score | +----+-------+-------+ | 1 | Chris | 45 | | 2 | David | 55 | | 3 | David | 98 | | 4 | Chris | 91 | | 5 | Mike | 99 | | 6 | Carol | 55 | +----+-------+-------+ 6 rows in set (0.00 sec)
Here is the query to get multiple counts in a single MySQL query −
mysql> select sum(Name='Chris'),sum(Score=55) from DemoTable1790;
This will produce the following output −
+-------------------+---------------+ | sum(Name='Chris') | sum(Score=55) | +-------------------+---------------+ | 2 | 2 | +-------------------+---------------+ 1 row in set (0.00 sec)
Advertisements