Computer >> Máy Tính >  >> Lập trình >> MySQL

Chọn và thêm kết quả nhân hai cột từ một bảng trong MySQL?

Bạn có thể sử dụng hàm tổng hợp SUM () cho việc này. Đầu tiên chúng ta hãy tạo một bảng -

mysql> create table DemoTable
   (
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerProductName varchar(100),
   CustomerProductQuantity int,
   CustomerPrice int
   );
Query OK, 0 rows affected (0.17 sec)

Chèn một số bản ghi vào bảng bằng lệnh chèn -

mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',5,400);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-2',3,100);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',2,300);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',5,50);
Query OK, 1 row affected (0.08 sec)

mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-3',6,10);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-2',10,20);
Query OK, 1 row affected (0.03 sec)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select -

mysql> select *from DemoTable;

Điều này sẽ tạo ra kết quả sau -

+------------+---------------------+-------------------------+---------------+
| 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            |
+------------+---------------------+-------------------------+---------------+
6 rows in set (0.00 sec)

Sau đây là truy vấn để chọn và thêm kết quả nhân hai cột (CustomerProductQuantity * CustomerPrice) từ một bảng trong MySQL.

mysql> select CustomerProductName,
SUM(CustomerProductQuantity*CustomerPrice) AS TOTAL_PRICE
from DemoTable
group by CustomerProductName;

Điều này sẽ tạo ra kết quả sau -

+---------------------+-------------+
| CustomerProductName | TOTAL_PRICE |
+---------------------+-------------+
| Product-1           | 2850        |
| Product-2           | 500         |
| Product-3           | 60          |
+---------------------+-------------+
3 rows in set (0.00 sec)