如何计算 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)
广告