- 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
MySQL select to count values equal to 0 and greater than 0 from a column?
For this, use the CASE statement. Let us first create a table −
mysql> create table DemoTable ( Number int ); Query OK, 0 rows affected (0.83 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(50); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+--------+ | Number | +--------+ | 10 | | 0 | | 20 | | 50 | | 0 | | 0 | | 40 | +--------+ 7 rows in set (0.00 sec)
Let us now see how to select count values equal to 0 and greater than 0 from a column
mysql> select sum(case when Number > 0 then 1 else 0 end ) AS TotalValueWhichIsGreaterThanZero, sum(case when Number = 0 then 1 else 0 end) AS TotalValueWhichIsEqualToZero from DemoTable where Number >=0;
Output
+----------------------------------+------------------------------+ | TotalValueWhichIsGreaterThanZero | TotalValueWhichIsEqualToZero | +----------------------------------+------------------------------+ | 4 | 3 | +----------------------------------+------------------------------+ 1 row in set (0.00 sec)
Advertisements