使用 MySQL 在单独的列中显示某一列的正值和负值之和
mysqlmysqli database更新于 2025/11/5 1:48:17
为此,您可以使用 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)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

