在 MySQL 中计算正负投票数?
要计算正负票数,您可以使用 CASE 语句以及聚合函数 SUM()。
让我们首先创建一个表 −
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)
广告