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

คูณสองคอลัมน์แล้วหาผลรวมตามกลุ่มใน MySQL

ใช้ SUM(คอลัมน์1 * คอลัมน์2) ร่วมกับ GROUP BY เพื่อคำนวณมูลค่ารวมต่อกลุ่ม

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

mysql> CREATE TABLE DemoTable (
    CustomerId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    CustomerProductName VARCHAR(100),
    CustomerProductQuantity INT,
    CustomerPrice INT
);
mysql> INSERT INTO DemoTable(CustomerProductName, CustomerProductQuantity, CustomerPrice) VALUES
    ('Product-1', 5, 400), ('Product-2', 3, 100), ('Product-1', 2, 300),
    ('Product-1', 5, 50), ('Product-3', 6, 10), ('Product-2', 10, 20);

ดูข้อมูล

mysql> SELECT * FROM DemoTable;
+------------+---------------------+-------------------------+---------------+
| CustomerId | CustomerProductName | CustomerProductQuantity | CustomerPrice |
+------------+---------------------+-------------------------+---------------+
|          1 | Product-1           |                       5 |           400 |
|          2 | Product-2           |                       3 |           100 |
|          3 | Product-1           |                       2 |           300 |
|          4 | Product-1           |                       5 |            50 |
|          5 | Product-3           |                       6 |            10 |
|          6 | Product-2           |                      10 |            20 |
+------------+---------------------+-------------------------+---------------+

คำนวณมูลค่ารวมต่อสินค้า (Quantity × Price)

mysql> SELECT CustomerProductName,
    -> SUM(CustomerProductQuantity * CustomerPrice) AS TOTAL_PRICE
    -> FROM DemoTable
    -> GROUP BY CustomerProductName;

ผลลัพธ์

+---------------------+-------------+
| CustomerProductName | TOTAL_PRICE |
+---------------------+-------------+
| Product-1           |        2850 |
| Product-2           |         500 |
| Product-3           |          60 |
+---------------------+-------------+

การคำนวณ Product-1: (5×400) + (2×300) + (5×50) = 2000 + 600 + 250 = 2850