Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

MySQL SELECT และ SUM แบบจัดกลุ่มด้วย GROUP BY

ใช้ฟังก์ชันรวม SUM() ร่วมกับ GROUP BY เพื่อคำนวณผลรวมของคอลัมน์ตัวเลขในแต่ละกลุ่ม

ตัวอย่างการใช้งาน

1. สร้างตารางสินค้า

mysql> CREATE TABLE DemoTable (
    ProductName VARCHAR(20),
    ProductQuantity INT,
    ProductPrice INT
);
Query OK, 0 rows affected (0.63 sec)

2. เพิ่มข้อมูลทดสอบ

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)

3. แสดงข้อมูลทั้งหมด

mysql> SELECT * FROM DemoTable;
+-------------+-----------------+--------------+
| ProductName | ProductQuantity | ProductPrice |
+-------------+-----------------+--------------+
| Product-1   |               2 |           50 |
| Product-2   |               3 |           80 |
| Product-2   |               4 |          100 |
| Product-1   |               4 |          150 |
+-------------+-----------------+--------------+

4. คำสั่ง SELECT พร้อม SUM และ GROUP BY

mysql> SELECT *, SUM(ProductQuantity * ProductPrice) AS Total
    -> FROM DemoTable
    -> GROUP BY ProductName;

5. ผลลัพธ์

+-------------+-----------------+--------------+-------+
| ProductName | ProductQuantity | ProductPrice | Total |
+-------------+-----------------+--------------+-------+
| Product-1   |               2 |           50 |   700 |
| Product-2   |               3 |           80 |   640 |
+-------------+-----------------+--------------+-------+

คำอธิบาย

  • SUM(ProductQuantity * ProductPrice) : คำนวณมูลค่ารวมต่อแถว (จำนวน × ราคา) แล้วบวกรวมในแต่ละกลุ่ม
  • GROUP BY ProductName : จัดกลุ่มข้อมูลตามชื่อสินค้า
  • คอลัมน์ ProductQuantity และ ProductPrice ที่แสดงในผลลัพธ์จะเป็นค่าจากแถวแรกของแต่ละกลุ่ม (MySQL อนุญาตให้ SELECT คอลัมน์ที่ไม่ได้อยู่ใน GROUP BY หรือ Aggregate Function)

แนวทางปฏิบัติที่ดีกว่า (Best Practice)

ควรระบุเฉพาะคอลัมน์ที่ต้องการใน SELECT และใช้ Aggregate Function สำหรับคอลัมน์อื่น:

mysql> SELECT 
    ProductName,
    SUM(ProductQuantity) AS TotalQuantity,
    SUM(ProductQuantity * ProductPrice) AS TotalRevenue
    FROM DemoTable
    GROUP BY ProductName;