Oracle - GROUP BY 절, HAVING 절

uglyduck.dev·2020년 9월 27일
0

따라해보기 🎭

목록 보기
9/12

GROUP BY 절

GROUP BY절 vs HAVING절

부서별 급여 합계

SELECT DEPARTMENT_ID, SUM(salary)
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID;
DEPARTMENT_IDSUM(SALARY)
10051608
3024900
(NULL)7000

부서별 사원수와 평균 급여를 구해보자

SELECT DEPARTMENT_ID, SUM(salary), COUNT(salary), AVG(salary) 
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID;
DEPARTMENT_IDSUM(SALARY)COUNT(SALARY)AVG(SALARY)
1005160868601.3333...
302490064150
(NULL)700017000
201900029500
  • GROUPT BY 절의 컬럼과, SELECT 절의 컬럼은 동일해야 함.

부서별, 직급별 사원수와 평균 급여를 구하고 부서 ID기준으로 오름차순으로 정렬

SELECT DEPARTMENT_ID, JOB_ID, SUM(salary), COUNT(salary), AVG(salary)
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID, JOB_ID;
ORDER BY DEPARTMENT_ID, JOB_ID;
DEPARTMENT_IDJOB_IDSUM(SALARY)COUNT(SALARY)AVG(SALARY)
10AD_ASST44001...
20MK_MAN130001...
20MK_RED60001...
30PU_CLERK139005...
  • GROUP BY 절의 컬럼과, SELECT 절의 컬럼은 동일해야 함.

TO_CHAR() 함수를 이용해서 출력값 형태 변경하기

SELECT DEPARTMENT_ID, JOB_ID,
    TO_CHAR(SUM(salary), '999,999') 총급여,
    TO_CHAR(AVG(salary), '999,999') 평균급여
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID, JOB_ID;
ORDER BY DEPARTMENT_ID,JOB_ID;
DEPARTMENT_IDJOB_ID총급여평균급여
10AD_ASST4,4004,400
20MK_MAN13,00013,000
20MK_REP6,0006,000
30PU_CLERK13,9002,780
30PU_MAN11,00011,000
40HR_REP6,5006,500
50SH_CLERK64,4003,215

HAVING 절

현재 부서별 사원수가 10명 이상인 경우

SELECT DEPARTMENT_ID, COUNT(*)
FROM EMPLOYEES
WHERE DEPARTMENT_ID IS NOT NULL
GROUP BY DEPARTMENT_ID
HAVING COUNT(*) >= 10;
DEPARTMENT_IDCOUNT(*)
5045
8034

ROLLUP()

  • 그룹별 합계 정보를 추가해서 보여주는 함수
SELECT L.CITY, D.DEPARMENT_NAME, E.JOB_ID,
    COUNT(*) 사원수, SUM(E.SALARY) 총급여
FROM EMPLOYEES E, DEPARTMENTS D, LOCATIONS L
WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID
    AND D.LOCATION_ID = L.LOCATION_ID
GROUP BY ROLLUP(L.CITY, D.DEPARTMENT_NAME, E.JOB_ID)
ORDER BY L.CITY, D.DEPARTMENT_NAME, E.JOB_ID;
  • ROLLUP() 함수 적용 전
CITYDEPARTMENT_NAMEJOB_ID사원수총급여
LondonHuman ResourcesHR_REP16500
MunichPublic RelationsPR_REP110000
OxfordSalesSA_MAN561000
SeattleAccountingAC_ACCOUNT18300
South San FranciscoShippingSH_CLERK2064300
  • ROLLUP() 함수 적용 후
CITYDEPARTMENT_NAMEJOB_ID사원수총급여
LondonHuman ResourcesHR_REP16500
MunichPublic RelationsPR_REP110000
OxfordSalesSA_MAN561000
SeattleAccountingAC_ACCOUNT18300
South San FranciscoShippingSH_CLERK2064300

Reference

profile
시행착오, 문제해결 그 어디 즈음에.

0개의 댓글