8. GROUP 함수 & GROUP BY 절

박은서's avatar
Apr 24, 2026
8. GROUP 함수 & GROUP BY 절

1. GROUP 함수 & GROUP BY 절

1️⃣ GROUP 함수

1) COUNT(개수)

-- group 함수 select count(sal) from emp;
notion image
select count(sal), ename from emp;
notion image
→ 행의 개수가 맞지 않으면 실행되지 않음

2) SUM(합계)

select sum(sal) from emp;
notion image
select sum(sal) from emp where job = 'manager';
notion image

3) AVG(평균)

select avg(sal) from emp;
notion image
select ceil(avg(sal)) from emp;
notion image

4) MAX(최대값)

select max(sal) from emp;
notion image

5) MIN(최소값)

select min(sal) from emp;
notion image

2️⃣ GROUP BY 절

1) GROUP BY절이란?

  • GROUP 함수는 전체 행을 하나의 그룹으로 보고 하나의 행으로 집계하는 것
  • GROUP BY 절은 같은 데이터끼리 그룹으로 묶어 그룹의 횟수만큼 나옴

2) HAVING절

  • group by 절에서는 where 절을 쓸 수 없기 때문에 having 절을 사용
  • group by 절의 where
select grade, avg(height) from student group by grade having avg(height) < 170;
notion image

3) 인라인뷰

  • Having을 사용하는 대신 임의로 만든 view를 테이블(from)로 가져와서 조건(where)을 걸 수 있음
  • 하나의 명령문에 SELECT가 두 번 이상 나오는 것을 서브 쿼리라고 하는데
    • 그 중에서도 FROM절에서 SELECT를 하는 것을 인라인뷰라고 함
select grade, avg_height from ( select grade, avg(height) avg_height from student group by grade) e where avg_height < 170;
notion image

4) 실행 순서

fromwheregroup byhavingselectorder by

5) 실습

-- 5개의 그룹으로 만들어짐 (행5개) -- clerk [1, 11, 12, 14] -- salesman [2, 3, 5, 10] -- manager [4, 6, 7] -- analyst [8, 13] -- president [9] select job from emp group by job; -- 1개의 그룹으로 만들어짐 -- sum은 그룹함수인데, 전체 행을 연산 select sum(sal) from emp; -- clerk [1, 11, 12, 14] -> sum (clerk, sum결과) -- salesman [2, 3, 5, 10] -> sum (salesman, sum결과) -- manager [4, 6, 7] -> sum (manager, sum결과) -- analyst [8, 13] -> sum (analyst, sum결과) -- president [9] -> sum (president, sum결과) select job, sum(sal) from emp group by job;
notion image
notion image
notion image
  • 에러나는 경우
    • select job, sum(sal), ename from emp group by job;
      notion image
      → 이 경우 ename은 행이 14개이기 때문에 에러 남

6) 연습 문제

같은 나이끼리 그룹을 지어서, 키의 평균을 구하시오
select year(birthday), truncate(avg(height),1) from student group by year(birthday);
notion image
 
Share article