在 MySQL 中使用分组进行选择和求和?
mysqlmysqli database更新于 2024/8/31 4:28:17
要求和,请使用聚合函数 SUM()。然后,使用 MySQL GROUP BY 进行分组。让我们首先创建一个表 −
mysql> create table DemoTable -> ( -> ProductName varchar(20), -> ProductQuantity int, -> ProductPrice int -> ); Query OK, 0 rows affected (0.63 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('Product-1',2,50);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Product-2',3,80);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Product-2',4,100);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Product-1',4,150);
Query OK, 1 row affected (0.11 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+-------------+-----------------+--------------+ | ProductName | ProductQuantity | ProductPrice | +-------------+-----------------+--------------+ | Product-1 | 2 | 50 | | Product-2 | 3 | 80 | | Product-2 | 4 | 100 | | Product-1 | 4 | 150 | +-------------+-----------------+--------------+ 4 rows in set (0.00 sec)
以下是在 MySQL 中使用分组选择的查询 −
mysql> select *,sum(ProductQuantity*ProductPrice) as Total from DemoTable -> group by ProductName;
这将产生以下输出 −
+-------------+-----------------+--------------+-------+ | ProductName | ProductQuantity | ProductPrice | Total | +-------------+-----------------+--------------+-------+ | Product-1 | 2 | 50 | 700 | | Product-2 | 3 | 80 | 640 | +-------------+-----------------+--------------+-------+ 2 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

