inblog logo
|
jjack1
    MySQL데이터베이스

    [DB] 4. SELECT 복합 행 함수

    최재원's avatar
    최재원
    Feb 26, 2025
    [DB] 4. SELECT 복합 행 함수
    Contents
    1. Group 함수1. COUNT2. SUM3. AVG4. MIN5. MAX2. 원하는 행만 세로 연산 하기3. 그룹핑 하기1. 동일한 값 스쿼시2. union all3. group by⭐4. having4. 실습

    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와 그룹함수 - 전체를 그룹화로 나눔
    그룹핑 연산 예시
    1. 전체 데이터 퍼 올리기
    notion image
    1. 그룹을 기준으로 정렬
    notion image
    1. 각 그룹 별로 연산을 실행
    notion image
    1. 연산 된 결과를 출력
    • deptno 값이 동일하니 압축해서 하나로 보여줌

     
    select avg(weight) from student where year(birthday) = 1975; select avg(weight) from student where substr(jumin, 1, 2) = 75;
    notion image
    select floor(avg(pay)) from professor where position = '정교수';
    notion image
    select min(height) from student;
    notion image

    3. 그룹핑 하기

    1. 동일한 값 스쿼시

    select avg(sal), deptno from emp where deptno = 10;
    notion image
    • 세로열의 값이 동일하면 스쿼시(찌그러트려) 사용

    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;
    notion image
    • where 결과만 가져와서 합치기

    3. group by⭐

    select avg(sal), deptno from emp group by deptno;
    notion image
    • 특정 컬럼을 그룹화 해서 연산

    4. having

    select job, deptno, avg(sal) from emp group by job, deptno having deptno != 10;
    notion image
    • 그룹핑 한 것들을 where을 하는 방법
    • 그룹핑 조건
    select avg(sal), deptno from emp group by deptno having avg(sal) > 2000;
    notion image
    • 그룹화 한 다음 where로 특정하고 싶다면 having을 사용한다.
    • 잘 쓰지 않는다.

    4. 실습

    학년을 기준으로 키 평균값 확인

    select grade, avg(height) from student group by grade;
    notion image

    직업과 부서를 기준으로 연봉 평균값 확인

    select job, deptno, avg(sal) from emp group by job, deptno;
    notion image

    연봉이 500 이상인 그룹 미만인 그룹 별로 연봉 평균값 확인

    select avg(pay), case when pay >= 500 then '고연봉' else '일반연봉' end from professor group by case when pay >= 500 then '고연봉' else '일반연봉' end;
    notion image
     
    Share article

    jjack1

    RSS·Powered by Inblog