SUM() 집계 함수와 GROUP BY를 함께 사용하면 그룹별 합계를 쉽게 계산할 수 있습니다.
테이블 생성 및 데이터 삽입
mysql> CREATE TABLE DemoTable (
-> ProductName VARCHAR(20),
-> ProductQuantity INT,
-> ProductPrice INT
-> );
Query OK, 0 rows affected (0.63 sec)
mysql> INSERT INTO DemoTable VALUES('Product-1',2,50);
Query OK, 1 row affected (0.16 sec)
mysql> INSERT INTO DemoTable VALUES('Product-2',3,80);
Query OK, 1 row affected (0.10 sec)
mysql> INSERT INTO DemoTable VALUES('Product-2',4,100);
Query OK, 1 row affected (0.11 sec)
mysql> INSERT INTO DemoTable VALUES('Product-1',4,150);
Query OK, 1 row affected (0.11 sec)
데이터 조회
mysql> SELECT * FROM DemoTable;
+-------------+-----------------+--------------+ | ProductName | ProductQuantity | ProductPrice | +-------------+-----------------+--------------+ | Product-1 | 2 | 50 | | Product-2 | 3 | 80 | | Product-2 | 4 | 100 | | Product-1 | 4 | 150 | +-------------+-----------------+--------------+ 4 rows in set (0.00 sec)
그룹별 총액 계산
mysql> SELECT *, SUM(ProductQuantity * ProductPrice) AS Total
-> FROM DemoTable
-> GROUP BY ProductName;
+-------------+-----------------+--------------+-------+ | ProductName | ProductQuantity | ProductPrice | Total | +-------------+-----------------+--------------+-------+ | Product-1 | 2 | 50 | 700 | | Product-2 | 3 | 80 | 640 | +-------------+-----------------+--------------+-------+ 2 rows in set (0.00 sec)
주의: SELECT *에 집계 함수를 함께 쓰면 MySQL은 ONLY_FULL_GROUP_BY 모드에서 에러를 낼 수 있습니다. 실무에선 그룹핑 컬럼과 집계 컬럼만 명시적으로 선택하는 것이 안전합니다.