Sử dụng SUM(column1 * column2) kết hợp GROUP BY để tính tổng thành tiền theo từng khách hàng.
Tạo bảng đơn hàng
mysql> CREATE TABLE DemoTable (
-> CustomerId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> CustomerName VARCHAR(100),
-> CustomerItems INT,
-> CustomerPrice INT
-> );
Chèn dữ liệu
mysql> INSERT INTO DemoTable(CustomerName, CustomerItems, CustomerPrice) VALUES('Larry', 3, 450);
mysql> INSERT INTO DemoTable(CustomerName, CustomerItems, CustomerPrice) VALUES('Mike', 2, 550);
mysql> INSERT INTO DemoTable(CustomerName, CustomerItems, CustomerPrice) VALUES('Larry', 4, 1000);
mysql> INSERT INTO DemoTable(CustomerName, CustomerItems, CustomerPrice) VALUES('Larry', 1, 100);
mysql> INSERT INTO DemoTable(CustomerName, CustomerItems, CustomerPrice) VALUES('Mike', 5, 200);
Xem dữ liệu chi tiết
mysql> SELECT * FROM DemoTable;
+------------+--------------+---------------+---------------+ | CustomerId | CustomerName | CustomerItems | CustomerPrice | +------------+--------------+---------------+---------------+ | 1 | Larry | 3 | 450 | | 2 | Mike | 2 | 550 | | 3 | Larry | 4 | 1000 | | 4 | Larry | 1 | 100 | | 5 | Mike | 5 | 200 | +------------+--------------+---------------+---------------+
Tính tổng tiền mỗi khách (Items × Price rồi SUM)
mysql> SELECT CustomerName, SUM(CustomerItems * CustomerPrice) AS TOTAL_PRICE
-> FROM DemoTable
-> GROUP BY CustomerName;
+--------------+-------------+ | CustomerName | TOTAL_PRICE | +--------------+-------------+ | Larry | 5450 | | Mike | 2100 | +--------------+-------------+
Phân tích tính toán
| Khách | Dòng | Items | Price | Thành tiền |
|---|---|---|---|---|
| Larry | 1 | 3 | 450 | 1,350 |
| 3 | 4 | 1000 | 4,000 | |
| 4 | 1 | 100 | 100 | |
| Tổng Larry | 5,450 | |||
| Mike | 2 | 2 | 550 | 1,100 |
| 5 | 5 | 200 | 1,000 | |
| Tổng Mike | 2,100 | |||
Mở rộng: Thêm số lượng đơn hàng
SELECT
CustomerName,
COUNT(*) AS OrderCount,
SUM(CustomerItems) AS TotalItems,
SUM(CustomerItems * CustomerPrice) AS TotalRevenue
FROM DemoTable
GROUP BY CustomerName;