MySQL 查詢來乘以兩行中的值並相加結果


為此,使用聚合函式SUM()。在該方法中,將行值相乘。我們首先建立一個表 -

mysql> create table DemoTable(
   ProductQuantity int,
   ProductPrice int
);
Query OK, 0 rows affected (0.48 sec)

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

mysql> insert into DemoTable values(10,9);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(6,20);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(7,100);
Query OK, 1 row affected (0.08 sec)

使用 select 語句從表中顯示所有記錄 -

mysql> select *from DemoTable;

這樣將產生以下輸出 -

+-----------------+--------------+
| ProductQuantity | ProductPrice |
+-----------------+--------------+
| 10              |            9 |
| 6               |           20 |
| 7               |          100 |
+-----------------+--------------+
3 rows in set (0.00 sec)

以下是查詢,可以相乘兩行中的值並相加結果 -

mysql> select SUM(ProductQuantity*ProductPrice) AS Total_Value from DemoTable;

這樣將產生以下輸出 -

+-------------+
| Total_Value |
+-------------+
| 910         |
+-------------+
1 row in set (0.00 sec)

更新於: 2019 年 9 月 3 日

977 次檢視

開啟你的 職業

完成課程,獲得認證

開始
廣告
© . All rights reserved.