在 MySQL 中进行分组选择和求和?


总计,使用聚合函数 SUM()。使用 MySQL GROUP BY 进行分组。首先创建一张表 -

mysql> create table DemoTable
   -> (
   -> ProductName varchar(20),
   -> ProductQuantity int,
   -> ProductPrice int
   -> );
Query OK, 0 rows affected (0.63 sec)

使用插入命令在表中插入一些记录 -

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)

更新日期:18-12-2019

569 浏览量

启动您的事业

完成课程获取认证

开始
广告
© . All rights reserved.