- 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 zero, NULL and distinct values except zero and NULL with a single MySQL query
Let us first create a table −
mysql> create table DemoTable( Value int ); Query OK, 0 rows affected (1.35 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.59 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.70 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+ | Value | +-------+ | 10 | | NULL | | 10 | | 0 | | 20 | | 10 | | 0 | | NULL | +-------+ 8 rows in set (0.00 sec)
Following is the query to group by on all values except null and 0 −
mysql> select sum(Value is null) as NumberOfNull, sum(Value=0) as NumberOfZero, count(distinct Value > 0) as ValueExceptZeroAndNull from DemoTable;
This will produce the following output −
+--------------+--------------+------------------------+ | NumberOfNull | NumberOfZero | ValueExceptZeroAndNull | +--------------+--------------+------------------------+ | 2 | 2 | 2 | +--------------+--------------+------------------------+ 1 row in set (0.00 sec)
Advertisements