在 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.