MySQL에서 하나의 쿼리로 두 개의 서로 다른 열 집계하기
MySQL에서는 CASE 문과 SUM() 함수를 조합하면 하나의 쿼리만으로 서로 다른 두 개의 열에 대한 조건부 카운트를 동시에 수행할 수 있습니다. 이 기법은 특정 조건을 만족하는 행의 개수를 여러 관점에서 한 번에 집계해야 할 때 매우 유용합니다.
개념을 이해하기 위해 먼저 예제 테이블을 생성해 보겠습니다.
1. 테이블 생성
아래 쿼리로 예제 테이블을 만듭니다.
mysql> create table CountDifferentDemo - > ( - > ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > ProductName varchar(20), - > ProductColor varchar(20), - > ProductDescription varchar(20) - > ); Query OK, 0 rows affected (1.06 sec)
테이블은 제품 ID(ProductId), 제품명(ProductName), 제품 색상(ProductColor), 제품 설명(ProductDescription)의 네 개 컬럼으로 구성되어 있습니다.
2. 데이터 삽입
INSERT 명령어를 사용하여 테이블에 레코드를 추가합니다.
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-1','Red','Used');
Query OK, 1 row affected (0.46 sec)
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-1','Blue','Used');
Query OK, 1 row affected (0.17 sec)
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-2','Green','New');
Query OK, 1 row affected (0.12 sec)
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-2','Blue','New');
Query OK, 1 row affected (0.14 sec)
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-3','Green','New');
Query OK, 1 row affected (0.21 sec)
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-4','Blue','Used');
Query OK, 1 row affected (0.20 sec)3. 전체 레코드 조회
SELECT 문으로 테이블의 모든 레코드를 확인합니다.
mysql> select *from CountDifferentDemo;
실행 결과는 다음과 같습니다.
+-----------+-------------+--------------+--------------------+ | ProductId | ProductName | ProductColor | ProductDescription | +-----------+-------------+--------------+--------------------+ | 1 | Product-1 | Red | Used | | 2 | Product-1 | Blue | Used | | 3 | Product-2 | Green | New | | 4 | Product-2 | Blue | New | | 5 | Product-3 | Green | New | | 6 | Product-4 | Blue | Used | +-----------+-------------+--------------+--------------------+ 6 rows in set (0.01 sec)
4. CASE 문으로 두 개의 열 동시 집계하기
이제 핵심인 단일 쿼리 작성입니다. 아래 쿼리는 제품명별로 그룹화한 후, 색상이 'Red'인 경우와 설명이 'New'인 경우를 각각 카운트합니다.
mysql> select ProductName, - > SUM(CASE WHEN ProductColor = 'Red' THEN 1 ELSE 0 END) AS Color, - > SUM(CASE WHEN ProductDescription = 'New' THEN 1 ELSE 0 END) AS Desciption - > from CountDifferentDemo - > group by ProductName;
실행 결과는 다음과 같습니다.
+-------------+-------+------------+ | ProductName | Color | Desciption | +-------------+-------+------------+ | Product-1 | 1 | 0 | | Product-2 | 0 | 2 | | Product-3 | 0 | 1 | | Product-4 | 0 | 0 | +-------------+-------+------------+ 4 rows in set (0.12 sec)
결과 해석
- Product-1: 빨간색(Red) 제품이 1개 있고, 새 제품(New)은 없습니다.
- Product-2: 빨간색 제품은 없고, 새 제품(New)이 2개 있습니다.
- Product-3: 빨간색 제품은 없고, 새 제품(New)이 1개 있습니다.
- Product-4: 빨간색 제품도, 새 제품도 없습니다.
동작 원리 정리
CASE 문은 각 행마다 조건을 평가하여 조건이 참이면 1, 거짓이면 0을 반환합니다. 이 값을 SUM() 함수로 합산하면 해당 조건을 만족하는 행의 개수가 됩니다. 이렇게 하면 COUNT() 함수를 여러 번 사용하거나 별도의 쿼리를 실행할 필요 없이, 하나의 쿼리로 여러 조건의 카운트를 동시에 얻을 수 있습니다.
또한 COUNT(CASE WHEN ... THEN 1 END) 형태를 사용해도 동일한 결과를 얻을 수 있으며, 조건이 더 복잡해지거나 집계 대상 열이 늘어나더라도 같은 패턴으로 확장할 수 있다는 점이 이 기법의 장점입니다.