본문 바로가기
데이터베이스설계

[데이터베이스설계] 3-6 집계함수, group by

by 젼젼39 2024. 11. 25.
집계함수 집계함수 Aggregate Function => relation의 컬럼에 나타나는 값들에 대해 기능 수행 [모아서 계산]
-      avg = average value
-      min = minimum value
-      max = maximum value
-      sum = sum of values
-      count = number of values
 

Q) find the average salary of instructors in the Computer Science department
=> select avg(salary)                                      //지금까지는 투플이 열거됐었음
    from instructor
    where dept_name = ‘Comp.Sci’
 

Q) find the total number of instructors who teach a course in the Spring 2018 semester
=> select count( distinct ID )             //중복제거. 교수의 수를 물었으니 중복 없애고 세기
    from teaches
    where semester = ‘Spring’ and year = 2018;
 

Q) find the number of tuples in the course relation          // 집계함수 안에 컬럼명 외에 *도 가능
=> select count ( * )                      //조건을 만족하는 모든 투플(레코드)의 수를 세게 됨
    from course
    where TRUE
 
집계함수 유무에 따라 결과 마지막에 set 만드는(SELECT) 방식이 달라짐  
                                                                                                                        //나머지 절에 대해서는 갈리지않음

* 집계함수 없는 경우 -> across the tuple
    =>  select B,C만 있다면 A는 지나쳐감.
    =>  투플의 컬럼들을 지나가면서 select된 컬럼들만 뽑음
 
* 집계함수 있는 경우 -> down the table
   => 테이블을 수직방향위에서 아래로 내려가면서
group by Group By -> 집계함수 사용할 때 사용
 
-      select절에 집계함수 없이 언급된 컬럼은 반드시 group by에 언급된 컬럼이어야 함
-      select절에 집계함수 여러 개 나와도 됨
-      group by의 기준이 되는 컬럼이 1개 이상 나와도 됨. 모두 동일한 것들끼리 하나로 묶는다
 

Q) find the average salary of instructors in each department  -> 학과별로 평균 내라
=> select dept_name, avg(salary) as avg_salary       //group by에 언급한 컬럼, 집계함수에 개명
    from instructor
    group by dept_name;                          //그룹별로 투플 하나씩 값을 채운다