使用 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)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP