1. Horizonal Calculation
- 세로 연산 (평균, 갯수, 합계, 최대, 최소)
-- 1. 그룹 함수
select avg(height)
from student;
select count(height)
from student;
select sum(height)
from student;
select max(height)
from student;
select min(height)
from student;

2. Horizonal Calculation 2
- 조건 추가 (where)
-- 2. 원하는 행만 세로 연산
select avg(weight)
from student
where year(birthday) = '1975';

-- 문제
select concat(floor(avg(pay)), '만 원')
from professor
where position = '정교수';
select avg(height)
from student;
- select avg(height), name from student; 를 실행할 수 없는 이유
- height의 평균이 출력되는 행에 넣을 이름이 없음
- Grouping이 필요


3. Grouping
-- 3. 그룹핑 하기
-- squash (동일한 값)
select *
from emp;
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;
- union all : 합집합
- 각자 다른 결과를 합쳐서 표시

Grouping 개념
select *
from emp
order by deptno asc;
select avg(sal), deptno
from emp
group by deptno;
- group by : 특정 값을 기준으로 우선 정렬 (order by)
- 정렬 후 동일한 값끼리 기준으로 연산
- 연산을 마친 후, 기준을 squash (압축)



4. Grouping Practices
- 기준을 여러 개 잡을 수 있음
- 이때, 기준별로 같은 값끼리 모여있다면 그 값 또한 기준으로 사용 가능
- ex) 직업별 부서의 평균 연봉
- 기준이 직업 → 부서
-- 4. 그룹핑 원리 실습
select *
from student;
-- 학년별 키의 평균
select avg(height), grade, substr(jumin, 1, 2)
from student
group by grade, jumin;
select *
from emp;
select job, avg(sal), deptno
from emp
group by job, deptno;


having
- 결과값에서 조건 추가
-- 평균 연봉이 2000 이상인 부서는?
select avg(sal), deptno
from emp
group by deptno
having avg(sal) > 2000;

SQL 실행 순서
- FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT

Share article