使用 MySQL 在单独的列中显示某列的正值和负值总和
为此,可以使用 CASE 语句。我们先创建一个表 −
mysql> create table DemoTable( Id int, Value int ); Query OK, 0 rows affected (0.51 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(10,100); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(10,-110); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(10,200); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(10,-678); Query OK, 1 row affected (0.17 sec)
使用 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)
广告