SQL 함수 - 집계함수

이승범·2024년 9월 15일

집계 함수(Aggregate Function)와 GROUP BY 절
집계 함수는 행 그룹을 기반으로 단일 결과를 반환
집계 함수는 select 절, having 및 order by 에서 사용 가능
집계 함수는 일반적으로 GROUP BY 절과 사용
테이블 전체가 하나의 그룹이 되는 경우 GROUP BY 없이 사용
GROUP BY 절에서 사용하지 않은 컬럼은 SELLECT 절에서 집계함수와 함께 사용 불가
SELECT dept, sum(sal) from emp; 일반컬럼인 dept와 sum()집계함수는 함께 사용 불가
COUNT(*),GROUPUNG,GROUPING_ID를 제외한 모든 집계함수는 NULL을 무시
COUNT 및 REG_COUNT는 레코드가 없는 경우 0을 반환

SCORE라는 컬럼에 90,NULL,90 데이터가 있을경우

AVG(SCORE) -- 90, NULL은 없는 데이터 취급함.
AVG(NVL(SCORE, 0) -- 60, SCORE가 NULL이면 0을 반환 90,0,90의 평균 180 / 3

COUNT(SCORE) --  2, SCORE의 데이터 개수, NULL은 없는 데이터 취급
COUNT(NVL(SCORE, 0) -- 3
COUNT(*) -- 3, NULL도 같이 셈, 전체 출력

MAX([ DISTINCT | ALL ] expr) : 최대값
MIN([ DISTINCT | ALL ] expr) : 최소값
SUM([ DISTINCT | ALL ] expr) : 합
AVG([ DISTINCT | ALL ] expr) : 평균
COUNT( * ) : 자료의 행 개수
COUNT( DISTINCT | ALL ] expr ) : 카운트, 말 그대로 세는것

다양한 집계함수 사용 예

-- 월별 입사 인원수, HIREDATE는 입사일자    
select count(*) 전체,
count(decode(to_char(hiredate,'MM'),'01',1))"1월",
count(decode(to_char(hiredate,'MM'),'02',1))"2월",
count(decode(to_char(hiredate,'MM'),'03',1))"3월",
count(decode(to_char(hiredate,'MM'),'04',1))"4월",
count(decode(to_char(hiredate,'MM'),'05',1))"5월",
count(decode(to_char(hiredate,'MM'),'06',1))"6월",
count(decode(to_char(hiredate,'MM'),'07',1))"7월",
count(decode(to_char(hiredate,'MM'),'08',1))"8월",
count(decode(to_char(hiredate,'MM'),'09',1))"9월",
count(decode(to_char(hiredate,'MM'),'10',1))"10월",
count(decode(to_char(hiredate,'MM'),'11',1))"11월",
count(decode(to_char(hiredate,'MM'),'12',1))"12월"
from 테이블명;

-- 여기서 SAL은 급여 컬럼, RRN은 주민등록번호 컬럼
-- SAL 전체 합, 여자 SAL 합, 남자 SAL 합
select '전체'구분, sum(sal)합 from 테이블명
            union all
select '남자', sum(sal) from 테이블명 where mod(substr(rrn,8,1),2) = 1
            union all
select '여자', sum(sal) from 테이블명 where mod(substr(rrn,8,1),2) = 0;

 -- 급여가 가장 높은 사람의 이름   
select name, sal
from emp
where sal = ( select max(sal) from emp ); 
-- 서브쿼리, where 절 연산자 = 다음에는 1개의 값만 올수있다

-- 가장 나이 많은 , 가장 어린 사람, RRN은 주민등록번호 컬럼
select min(substr(rrn,1, 6)), max(substr(rrn,1, 6)) from 테이블명;
      
select rrn from 테이블명 order by rrn;
       
select min(to_date(substr(rrn, 1, 6), 'RRMMDD')) old,
max(to_date(substr(rrn, 1, 6), 'RRMMDD')) young from 테이블명;
profile
creative

0개의 댓글