이를 위해 집계 함수 SUM()을 사용할 수 있습니다. 먼저 테이블을 생성하겠습니다 -
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)
삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -
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)
select 문을 사용하여 테이블의 모든 레코드 표시 -
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 | +------------+---------------------+-------------------------+---------------+ 6 rows in set (0.00 sec)
다음은 MySQL의 테이블에서 두 개의 열(CustomerProductQuantity*CustomerPrice)을 곱한 결과를 선택하여 추가하는 쿼리입니다.
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 | +---------------------+-------------+ 3 rows in set (0.00 sec)