要计算正面和负面投票的数量,您可以使用 CASE 语句和聚合函数SUM()。
让我们首先创建一个表 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Vote int );
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable(Vote) values(-10); mysql> insert into DemoTable(Vote) values(100); mysql> insert into DemoTable(Vote) values(45); mysql> insert into DemoTable(Vote) values(-6); mysql> insert into DemoTable(Vote) values(-1000); mysql> insert into DemoTable(Vote) values(450);
以下是使用 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)