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)
Updated on: 2019-10-09T12:07:56+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements