使用 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)

更新於: 2019 年 9 月 3 日

6 千+ 瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.