为此,您可以使用CASE语句。让我们首先创建一个表-
mysql> create table DemoTable( Id int, Value int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(10,100); mysql> insert into DemoTable values(10,-110); mysql> insert into DemoTable values(10,200); mysql> insert into DemoTable values(10,-678);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+------+-------+ | Id | Value | +------+-------+ | 10 | 100 | | 10 | -110 | | 10 | 200 | | 10 | -678 | +------+-------+ 4 rows in set (0.00 sec)
以下是查询以显示单独列中一列的正值和负值的总和-
mysql> select Id, sum(case when Value>0 then Value else 0 end) as Positive_Value, sum(case when Value<0 then Value else 0 end) as Negative_Value from DemoTable group by Id;
这将产生以下输出-
+------+----------------+----------------+ | Id | Positive_Value | Negative_Value | +------+----------------+----------------+ | 10 | 300 | -788 | +------+----------------+----------------+ 1 row in set (0.00 sec)