如何計算 MySQL 產品表中產品的總價值?


讓我們先建立一個表 -

mysql> create table DemoTable
   (
   ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ProductQuantity int,
   ProductPrice int
   );
Query OK, 0 rows affected (0.19 sec)

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

mysql> insert into DemoTable(ProductQuantity,ProductPrice) values(10,100);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(ProductQuantity,ProductPrice) values(5,11);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(ProductQuantity,ProductPrice) values(3,140);
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(ProductQuantity,ProductPrice) values(2,450);
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from DemoTable;

這將產生以下輸出 -

+-----------+-----------------+--------------+
| ProductId | ProductQuantity | ProductPrice |
+-----------+-----------------+--------------+
| 1         | 10              | 100          |
| 2         | 5               | 11           |
| 3         | 3               | 140          |
| 4         | 2               | 450          |
+-----------+-----------------+--------------+
4 rows in set (0.00 sec)

以下是對產品總值進行計算的查詢 -

mysql> select sum(ProductQuantity*ProductPrice) as Total_of_Products from DemoTable;

這將產生以下輸出 -

+-------------------+
| Total_of_Products |
+-------------------+
| 2375              |
+-------------------+
1 row in set (0.00 sec)

更新於: 2019-7-30

503 檢視次數

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告