- Trending Categories
- 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
Count multiple rows and display the result in different columns (and a single row) with MySQL
Let us first create a table −
mysql> create table DemoTable1452 -> ( -> FavouriteColor varchar(50) -> ); Query OK, 0 rows affected (2.42 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1452 values('Red'); Query OK, 1 row affected (0.31 sec) mysql> insert into DemoTable1452 values('Yellow'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1452 values('Yellow'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1452 values('Yellow'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable1452 values('Blue'); Query OK, 1 row affected (0.42 sec) mysql> insert into DemoTable1452 values('Blue'); Query OK, 1 row affected (0.33 sec) mysql> insert into DemoTable1452 values('Red'); Query OK, 1 row affected (0.29 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1452;
This will produce the following output −
+----------------+ | FavouriteColor | +----------------+ | Red | | Yellow | | Yellow | | Yellow | | Blue | | Blue | | Red | +----------------+ 7 rows in set (0.00 sec)
Following is the query to count multiple rows and display the result in different columns −
mysql> select sum(FavouriteColor='Red') as NumberOfRedColor, -> sum(FavouriteColor='Yellow') as NumberOfYellowColor, -> sum(FavouriteColor='Blue') as NumberOfBlueColor -> from DemoTable1452;
This will produce the following output −
+------------------+---------------------+-------------------+ | NumberOfRedColor | NumberOfYellowColor | NumberOfBlueColor | +------------------+---------------------+-------------------+ | 2 | 3 | 2 | +------------------+---------------------+-------------------+ 1 row in set (0.27 sec)
Advertisements