在MySQL中计算正负投票的数量?
要计算正负投票的数量,可以使用聚合函数SUM()和CASE语句。
让我们首先创建一个表 –
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Vote int
);
Query OK, 0 rows affected (1.70 sec)
使用insert命令在表中插入一些记录-
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)
以下是使用select语句显示表中所有记录的查询-
mysql> select *from DemoTable;
这将产生以下输出-
+----+-------+
| Id | Vote |
+----+-------+
| 1 | -10 |
| 2 | 100 |
| 3 | 45 |
| 4 | -6 |
| 5 | -1000 |
| 6 | 450 |
+----+-------+
6 rows in set (0.00 sec)
以下是计算正负投票数目的查询-
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;
这将产生以下输出-
+--------------------------+--------------------------+
| Number_Of_Positive_Votes | Number_Of_Negative_Votes |
+--------------------------+--------------------------+
| 3 | 3 |
+--------------------------+--------------------------+
1 row in set (0.00 sec)
阅读更多:MySQL 教程