일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- #코멘토 #코멘토실무PT #실무PT후기 #Google BigQuery # 대시보드
- #코멘토 #코멘토실무PT #실무PT후기 #Google BigQuery
- #패스트캠퍼스 #내일배움카드취업 #국비지원교육 #K디지털기초역량훈련 # 데이터시각화강의
- #코멘토 #코멘토실무PT #실무PT후기 #Google BigQuery # 자동화
- #코멘토 #코멘토실무PT #실무PT후기 #Google BigQuery # 전환율
문과생의 데이터 연습
Rollup 함수 사용하기! [MySQL] (2) 본문
MySQL에서 Rollup 함수 쓰는법!
전에 글에 이어서 rollup 함수를 추가적으로 알아보겠습니다!

실습은 똑같이 MySQL workbench에서 진행합니다!
1.) Rollup + grouping 함수
grouping 함수는 rollup 함수랑 잘어울리는 짝궁 함수라고 생각해요~
rollup함수를 썼을 때 생겼던 null 값을 원하는 다른 이름으로 바꿔줄 수 있습니다.
일단 grouping 함수 사용법부터 알아봅시다!
SELECT Continent, Region, GovernmentForm, round(sum(GNP)) as GNP_total,
grouping(Continent) as gr_Continent,
grouping(Region) as gr_Region,
grouping(GovernmentForm) as gr_GovernmentForm
FROM country
GROUP BY Continent, Region, GovernmentForm WITH ROLLUP ;
grouping 함수는 0, 1을 반환해줍니다.
1는 Null이 있는 곳에 나머지는 0으로 표시해줍니다.
grouping 함수의 특징을 이용해서 null값의 이름을 바꿔줄겁니다~

2.) Rollup + grouping + (COALESCE or IFNULL or IF문 or CASE문)
이제 null이름을 바꿔줄건데요
총 4가지 방법이 있습니다. 더 있으면 알려주세요 ㅋㅋ
사실 4개 다 같은 결과를 반환하기 때문에 원하시는거 쓰면 될 것 같습니다.
IFNULL
SELECT IFNULL(Continent,"ALL Continent") as Continent,
IFNULL(Region,"ALL Region") as Region,
IFNULL(GovernmentForm,"ALL GovernmentForm") as GovernmentForm,
round(sum(GNP)) as GNP_total
FROM country
GROUP BY Continent, Region, GovernmentForm WITH ROLLUP;
파랑색을 보시면 원래 Null값이었던 값들이 제가 설정해준 이름값으로 변환한 것을 볼 수 있습니다.
이렇게 하면 이해하기 더 쉽겠죠?^^
IFNULL(Continent,"ALL Continent")
쿼리문 해석을 하자면 만약 Continent(대륙)이 Null값이면 'All Continent" 로 바꿔주라는 의미입니다~
COALESCE
SELECT COALESCE(Continent,"ALL Continent") as Continent,
COALESCE(Region,"ALL Region") as Region,
COALESCE(GovernmentForm,"ALL GovernmentForm") as GovernmentForm,
round(sum(GNP)) as GNP_total
FROM country
GROUP BY Continent, Region, GovernmentForm WITH ROLLUP;
COALESCE 함수 역시 똑같은 값을 반환합니다~
IF문
SELECT
IF(grouping(Continent), 'ALL Contient', Continent) as Continent,
IF(grouping(Region), 'ALL Region', Region) as Region,
IF(grouping(GovernmentForm), 'ALL GovernmentForm', GovernmentForm) as GovernmentForm,
round(sum(GNP)) as GNP_total
FROM country
GROUP BY Continent, Region, GovernmentForm WITH ROLLUP ;
IF문도 마찬가지로 같은 값을 반환합니다.
만약 Continent 가 1이면 'All Contient" 를 나머지는 Continent 값을 그대로 반환하는 쿼리문 입니다.
Case문
SELECT
CASE grouping(Continent) WHEN 1 THEN 'ALL Contient' ELSE Continent END as Continent,
CASE grouping(Region) WHEN 1 THEN 'ALL Region' ELSE Region END as Region,
CASE grouping(GovernmentForm) WHEN 1 THEN 'ALL GovernmentForm' ELSE GovernmentForm END as GovernmentForm,
SUM(Population) as total_Pop
FROM country
GROUP BY Continent, Region, GovernmentForm WITH ROLLUP ;
Case문구 역시 해보시면 똑같이 나오고 해석은 IF문과 똑같이 해석해도 무관하다고 생각합니다^^
3.) 가독성있게 보여주기?
지금까지 잘 따라오셨나요?

이제부터는 조금도 가독성(?)있게 출력되는 데이터들의 순서를 바꿔볼까 합니다.
일반적으로 전체값 같은 요약결과가 앞에 먼저 쫙~~~ 하고 보여주면 좋잖아요? 그것을 해보겠습니다!
백문이 불여일견!
SELECT
IF(grouping(Continent), 'ALL Contient', Continent) as Continent,
IF(grouping(Region), 'ALL Region', Region) as Region,
IF(grouping(GovernmentForm), 'ALL GovernmentForm', GovernmentForm) as GovernmentForm,
round(sum(GNP)) as GNP_total
FROM country
WHERE Continent != 'Antarctica'
GROUP BY Continent, Region, GovernmentForm WITH ROLLUP
ORDER BY grouping(Continent, Region, GovernmentForm) DESC ;
grouping 함수를 order by 구문에 추가해서 내림차순으로 보여줍니다
첫번 째 행의 GNP값이 전체 GNP 총합이겠죠? 즉
SELECT round(sum(GNP)) as GNP_total
FROM country ;
위 쿼리랑 첫 번쨰 행의 GNP 합의 값은 같을 수밖에 없습니다
Case문을 써도 상관없습니다.
합계만! 보여주고 싶다면?
SELECT
IF(grouping(Continent), 'ALL Contient', Continent) as Continent,
IF(grouping(Region), 'ALL Region', Region) as Region,
IF(grouping(GovernmentForm), 'ALL GovernmentForm', GovernmentForm) as GovernmentForm,
round(sum(GNP)) as GNP_total
FROM country
WHERE Continent != 'Antarctica'
GROUP BY Continent, Region, GovernmentForm WITH ROLLUP
HAVING grouping(Continent, Region, GovernmentForm) != 0
ORDER BY grouping(Continent, Region, GovernmentForm) DESC ;
합계만 보여주고 싶다면 grouping 함수를 having절에 사용해서 0이 아닌것을 뽑으면 됩니다.
1이 null값(전체값)을 보여주기 떄문입니다.^^
Antarctica도 제거해줍시다 ㅋㅋ
이렇게 해서 with rollup의 심화(?) 사용법을 알아봤습니다.
틀린부분이나 피드백부분이 있으면 댓글 부탁드립니다. 감사합니다!

'SQL > MySQL' 카테고리의 다른 글
Lag & Lead 함수 사용하기! [MySQL] (2) (0) | 2022.04.29 |
---|---|
[MySQL] Lag & Lead 함수 사용하기! (1) (0) | 2022.04.29 |
Rank 함수 사용하기! [MySQL] (2) (0) | 2022.04.28 |
Rank 함수 사용하기! [MySQL] (1) (0) | 2022.04.28 |
[MySQL] Rollup 함수 사용하기! (1) (3) | 2022.04.27 |