MySQL 查询语句:对相同客户的相似列中的产品价格值进行求和,并将结果显示在同一列中
为此,请使用 SUM() 函数以及 GROUP BY 语句。让我们先创建一个表:
mysql> create table DemoTable ( CustomerName varchar(100), Product_1_Price int, Product_2_Price int ); Query OK, 0 rows affected (0.73 sec)
使用 INSERT 命令在表中插入一些记录:
mysql> insert into DemoTable values('John',67,89); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('David',769,890); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('David',987,1000); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('John',900,111); Query OK, 1 row affected (0.12 sec)
使用 SELECT 语句显示表中的所有记录:
mysql> select *from DemoTable;
这将产生以下输出:
+--------------+-----------------+-----------------+ | CustomerName | Product_1_Price | Product_2_Price | +--------------+-----------------+-----------------+ | John | 67 | 89 | | David | 769 | 890 | | David | 987 | 1000 | | John | 900 | 111 | +--------------+-----------------+-----------------+ 4 rows in set (0.00 sec)
以下是计算总值并为同一客户显示结果的查询:
mysql> select CustomerName,SUM(Product_1_Price) AS Total1,SUM(Product_2_Price) As Total2 from DemoTable group by CustomerName;
这将产生以下输出:
+--------------+--------+--------+ | CustomerName | Total1 | Total2 | +--------------+--------+--------+ | John | 967 | 200 | | David | 1756 | 1890 | +--------------+--------+--------+ 2 rows in set (0.00 sec)
广告