Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Tính tổng tích của hai cột (Số lượng × Đơn giá) theo nhóm trong MySQL

Để tính tổng doanh thu (Số lượng × Đơn giá) cho từng sản phẩm, dùng hàm tổng hợp SUM() kết hợp phép nhân trực tiếp trong truy vấn, sau đó GROUP BY theo tên sản phẩm.

Tạo bảng đơn hàng

mysql> CREATE TABLE DemoTable (
    CustomerId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    CustomerProductName VARCHAR(100),
    CustomerProductQuantity INT,
    CustomerPrice INT
);

Chèn dữ liệu đơn hàng

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);

Dữ liệu chi tiết

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 |
+------------+---------------------+-------------------------+---------------+

Truy vấn tính tổng doanh thu theo sản phẩm

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

Kết quả

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

Chi tiết tính toán

  • Product-1: (5×400) + (2×300) + (5×50) = 2000 + 600 + 250 = 2850
  • Product-2: (3×100) + (10×20) = 300 + 200 = 500
  • Product-3: (6×10) = 60

Mẹo: Nếu cần tính tổng toàn bảng (không nhóm), bỏ GROUP BY: SELECT SUM(Quantity * Price) FROM DemoTable;.