MySQL 查询对同一客户的类似列中的产品价格值求和,并在同一列中显示结果

mysqlmysqli database更新于 2025/12/24 4:28:17

为此,请使用 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)

相关文章


有用资源