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

คูณคอลัมน์แล้ว Sum กลุ่มตามลูกค้าใน MySQL

เมื่อต้องการคำนวณยอดรวมต่อลูกค้า โดยคูณ จำนวนสินค้า × ราคา แล้วรวมตามชื่อลูกค้า ให้ใช้ SUM(column1 * column2) ... GROUP BY

สร้างตาราง Order Details

mysql> create table DemoTable (
    CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    CustomerName varchar(100),
    CustomerItems int,
    CustomerPrice int
);

ข้อมูลออเดอร์ (Larry 3 รายการ, Mike 2 รายการ)

mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice) values
('Larry',3,450),('Mike',2,550),('Larry',4,1000),('Larry',1,100),('Mike',5,200);

ข้อมูลดิบ

+------------+--------------+---------------+---------------+
| CustomerId | CustomerName | CustomerItems | CustomerPrice |
+------------+--------------+---------------+---------------+
| 1          | Larry        | 3             | 450           |
| 2          | Mike         | 2             | 550           |
| 3          | Larry        | 4             | 1000          |
| 4          | Larry        | 1             | 100           |
| 5          | Mike         | 5             | 200           |
+------------+--------------+---------------+---------------+

คำสั่ง: คูณ Items×Price แล้ว SUM GROUP BY CustomerName

mysql> SELECT CustomerName, SUM(CustomerItems * CustomerPrice) AS TOTAL_PRICE 
FROM DemoTable GROUP BY CustomerName;

ผลลัพธ์

+--------------+-------------+
| CustomerName | TOTAL_PRICE |
+--------------+-------------+
| Larry        | 5450        |
| Mike         | 2100        |
+--------------+-------------+

การคำนวณรายละเอียด

CustomerItemsPriceSubtotal
Larry34501,350
Larry41,0004,000
Larry1100100
Larry Total5,450
Mike25501,100
Mike52001,000
Mike Total2,100

ขยาย: เพิ่ม COUNT, AVG, MIN, MAX

SELECT 
    CustomerName,
    COUNT(*) AS order_count,
    SUM(CustomerItems * CustomerPrice) AS total_revenue,
    AVG(CustomerItems * CustomerPrice) AS avg_order_value,
    MIN(CustomerItems * CustomerPrice) AS min_order,
    MAX(CustomerItems * CustomerPrice) AS max_order
FROM DemoTable 
GROUP BY CustomerName;

คำเตือน: NULL Values

  • ถ้า CustomerItems หรือ CustomerPrice เป็น NULL → ผลคูณ = NULL → SUM ข้าม NULL
  • ใช้ COALESCE(CustomerItems,0) * COALESCE(CustomerPrice,0) เพื่อป้องกัน

Index สำหรับ Query นี้

CREATE INDEX idx_customer_name ON DemoTable(CustomerName);