如何在 MySQL 中根據欄位值進行求和?


若要根據欄位值求和,請使用聚合函式 SUM() 和 CASE 語句。我們首先建立一個表 −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Price int,
   isValidCustomer boolean,
   FinalPrice int
   );
Query OK, 0 rows affected (0.23 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(20,false,40);
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(45,true,10);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(89,true,50);
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(200,false,100);
Query OK, 1 row affected (0.06 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

這將產生以下輸出 −

+----+-------+-----------------+------------+
| Id | Price | isValidCustomer | FinalPrice |
+----+-------+-----------------+------------+
| 1  | 20    | 0               | 40         |
| 2  | 45    | 1               | 10         |
| 3  | 89    | 1               | 50         |
| 4  | 200   | 0               | 100        |
+----+-------+-----------------+------------+
4 rows in set (0.00 sec)

以下是對 SQL 查詢以根據 MySQL 中的欄位值求和。在這裡,FinalPrice 將新增到 FALSE (0),而 PRICE 將新增到 TRUE(1) −

mysql> select sum(case when isValidCustomer=true then Price else FinalPrice end) as TotalPrice from DemoTable;

這將產生以下輸出 −

+------------+
| TotalPrice |
+------------+
| 274        |
+------------+
1 row in set (0.00 sec)

更新於: 2019-07-30

321 檢視

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告