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

รวมราคาสินค้าต่อลูกค้าเดียวกันด้วย SUM() และ GROUP BY ใน MySQL

การคำนวณยอดรวมต่อลูกค้าด้วย SUM() และ GROUP BY

เมื่อมีตารางเก็บราคาสินค้าหลายรายการต่อลูกค้าเดียวกัน เราสามารถรวมยอดรวมต่อลูกค้าได้โดยใช้ SUM() ร่วมกับ GROUP BY CustomerName

สร้างตารางและเพิ่มข้อมูล

mysql> CREATE TABLE DemoTable (
    CustomerName VARCHAR(100),
    Product_1_Price INT,
    Product_2_Price INT
);
Query OK, 0 rows affected (0.73 sec)

mysql> INSERT INTO DemoTable VALUES('John',67,89);
mysql> INSERT INTO DemoTable VALUES('David',769,890);
mysql> INSERT INTO DemoTable VALUES('David',987,1000);
mysql> INSERT INTO DemoTable VALUES('John',900,111);

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

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)

คำอธิบาย

  • GROUP BY CustomerName : จัดกลุ่มแถวตามชื่อลูกค้า
  • SUM(Product_1_Price) : รวมราคาสินค้าที่ 1 ในแต่ละกลุ่ม
  • SUM(Product_2_Price) : รวมราคาสินค้าที่ 2 ในแต่ละกลุ่ม
  • John: Product1 = 67+900=967, Product2 = 89+111=200
  • David: Product1 = 769+987=1756, Product2 = 890+1000=1890