选择并添加从MySQL中的表中将两列相乘的结果?
您可以SUM()
为此使用聚合函数。让我们首先创建一个表-
mysql> create table DemoTable ( CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerProductName varchar(100), CustomerProductQuantity int, CustomerPrice int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',5,400); mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-2',3,100); mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',2,300); mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',5,50); mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-3',6,10); mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-2',10,20);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+------------+---------------------+-------------------------+---------------+ | CustomerId | CustomerProductName | CustomerProductQuantity | CustomerPrice | +------------+---------------------+-------------------------+---------------+ | 1 | Product-1 | 5 | 400 | | 2 | Product-2 | 3 | 100 | | 3 | Product-1 | 2 | 300 | | 4 | Product-1 | 5 | 50 | | 5 | Product-3 | 6 | 10 | | 6 | Product-2 | 10 | 20 | +------------+---------------------+-------------------------+---------------+ 6 rows in set (0.00 sec)
以下是查询并选择和添加从MySQL中的表中将两列(CustomerProductQuantity*CustomerPrice)相乘的结果的查询。
mysql> select CustomerProductName, SUM(CustomerProductQuantity*CustomerPrice) AS TOTAL_PRICE from DemoTable group by CustomerProductName;
这将产生以下输出-
+---------------------+-------------+ | CustomerProductName | TOTAL_PRICE | +---------------------+-------------+ | Product-1 | 2850 | | Product-2 | 500 | | Product-3 | 60 | +---------------------+-------------+ 3 rows in set (0.00 sec)