- 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 values greater and less than a specific number and display count in separate MySQL columns?
For this, you can use COUNT() along with CASE STATEMENT. Let us first create a table −
mysql> create table DemoTable ( Score int ); Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.77 sec) mysql> insert into DemoTable values(48); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(59); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(33); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(38); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(89); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(35); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+ | Score | +-------+ | 40 | | 48 | | 59 | | 33 | | 38 | | 89 | | 35 | +-------+ 7 rows in set (0.00 sec)
Following is the query to count values greater and less than a specific number and display count in separate columns −
mysql> select count( case when Score > 45 then 1 end) as CountOfValueGreaterThan45, count( case when Score <= 45 then 1 end) as CountOfValueLessThanOrEqualTo45 from DemoTable;
This will produce the following output −
+---------------------------+---------------------------------+ | CountOfValueGreaterThan45 | CountOfValueLessThanOrEqualTo45 | +---------------------------+---------------------------------+ | 3 | 4 | +---------------------------+---------------------------------+ 1 row in set (0.00 sec)
Advertisements