728x90
Activities 테이블에서 sell_date를 기준으로 GROUP BY를 한 후 그룹핑된 product를 기준으로 count를 구하고, 최종적으로 해당 그룹에 제품들을 콤마 로 구분하여 하나로 합쳐 결과를 반환하는 SQL을 작성하는 문제이다.
처음엔 이전 문제를 풀면서 CONCAT(문자열 합쳐주는 함수) 를 알게 되었고 이를 사용하여 문제를 해결하려고 시도 하였다. 풀이가 도저히 생각나지 않아 솔루션을 확인한 결과 GROUP_CONCAT 이라는 것을 새롭게 알게 되었다.
GROUP_CONCAT사용법은 다음과 같다.
select type, group_concat(name) from test group by type ;
type |
name |
fruit | 수박,사과,바나나,사과 |
group_concat을 기본적인 형태로 사용했을경우 문자열 사이에 쉼표(,)가 붙게 된다.
구분자를 변경하고 싶을때는 아래와 같이 SEPARATOR '구분자' 를 붙여 준다.
select type, group_concat(name separator '|') from test group by type ;
type |
name |
fruit | 수박|사과|바나나|사과 |
합쳐지는 문자열에 중복되는 문자열을 제거 할때는 distinct 를 사용한다.
select type, group_concat(distinct name) from test group by type ;
type |
name |
fruit | 수박,사과,바나나 |
group_concat과 마찬가지로 count 함수 안에 distinct도 사용 가능 하다.
select sell_date, count(distinct product) as num_sold, group_concat(distinct product separator ',') as products
from Activities
group by sell_date
order by sell_date asc
반응형
'데이터베이스 > SQL' 카테고리의 다른 글
181. Employees Earning More Than Their Managers (0) | 2023.01.05 |
---|---|
1527. Patients With a Condition (0) | 2022.12.07 |
1667. Fix Names in a Table (0) | 2022.12.05 |
196. Delete Duplicate Emails (0) | 2022.12.05 |
627. Swap Salary (0) | 2022.12.03 |