Counting number of positive and negative votes in MySQL?

MySQLMySQLi Database

To count number of positive and negative votes, you can use CASE statement along with aggregate function SUM().

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Vote int
);
Query OK, 0 rows affected (1.70 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Vote) values(-10);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Vote) values(100);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Vote) values(45);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Vote) values(-6);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Vote) values(-1000);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Vote) values(450);
Query OK, 1 row affected (0.14 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+
| Id | Vote  |
+----+-------+
| 1  | -10   |
| 2  | 100   |
| 3  | 45    |
| 4  | -6    |
| 5  | -1000 |
| 6  | 450   |
+----+-------+
6 rows in set (0.00 sec)

Following is the query to count number of positive and negative votes −

mysql> select sum(case when Vote > 0 then 1 else 0 end) as Number_Of_Positive_Votes,
sum(case when Vote < 0 then 1 else 0 end) as Number_Of_Negative_Votes
from DemoTable;

This will produce the following output −

+--------------------------+--------------------------+
| Number_Of_Positive_Votes | Number_Of_Negative_Votes |
+--------------------------+--------------------------+
| 3                        | 3                        |
+--------------------------+--------------------------+
1 row in set (0.00 sec)
raja
Published on 29-Apr-2019 07:10:34
Advertisements