1. Group 함수
1. COUNT
select count(height)
from student;
2. SUM
select sum(height)
from student;
3. AVG
select avg(height)
from student;
4. MIN
select min(height)
from student;
5. MAX
select max(height)
from student;
2. 원하는 행만 세로 연산 하기
- 전체 행을 세로 연산 하려면? sum, max, avg 등 (그룹함수)
- 특정 행들을 세로 연산 하려면? where과 그룹함수 - 특정행만 골라냄
- 특정 그룹만 세로 연산 하려면? where과 그룹함수 - 특정행만 골라냄
- 그룹 별로 세로 연산 하려면? group by와 그룹함수 - 전체를 그룹화로 나눔
그룹핑 연산 예시
- 전체 데이터 퍼 올리기

- 그룹을 기준으로 정렬

- 각 그룹 별로 연산을 실행

- 연산 된 결과를 출력
- deptno 값이 동일하니 압축해서 하나로 보여줌
select avg(weight)
from student
where year(birthday) = 1975;
select avg(weight)
from student
where substr(jumin, 1, 2) = 75;

select floor(avg(pay))
from professor
where position = '정교수';

select min(height)
from student;

3. 그룹핑 하기
1. 동일한 값 스쿼시
select avg(sal), deptno
from emp
where deptno = 10;

- 세로열의 값이 동일하면 스쿼시(찌그러트려) 사용
2. union all
select avg(sal), deptno
from emp
where deptno = 10
union all -- 결과 합치기
select avg(sal), deptno
from emp
where deptno = 20
union all
select avg(sal), deptno
from emp
where deptno = 30;

- where 결과만 가져와서 합치기
3. group by⭐
select avg(sal), deptno
from emp
group by deptno;

- 특정 컬럼을 그룹화 해서 연산
4. having
select job, deptno, avg(sal)
from emp
group by job, deptno
having deptno != 10;

- 그룹핑 한 것들을 where을 하는 방법
- 그룹핑 조건
select avg(sal), deptno
from emp
group by deptno
having avg(sal) > 2000;

- 그룹화 한 다음 where로 특정하고 싶다면 having을 사용한다.
- 잘 쓰지 않는다.
4. 실습
학년을 기준으로 키 평균값 확인
select grade, avg(height)
from student
group by grade;

직업과 부서를 기준으로 연봉 평균값 확인
select job, deptno, avg(sal)
from emp
group by job, deptno;

연봉이 500 이상인 그룹 미만인 그룹 별로 연봉 평균값 확인
select
avg(pay),
case
when pay >= 500 then '고연봉'
else '일반연봉'
end
from professor
group by
case
when pay >= 500 then '고연봉'
else '일반연봉'
end;

Share article