inblog logo
|
parangdajavous
    Data Base

    [Data Base] 4. SELECT 복수행 함수

    김미숙's avatar
    김미숙
    Feb 26, 2025
    [Data Base] 4. SELECT 복수행 함수
    Contents
    1. 그룹함수 2. Group by 해서 연산하기
    ‼️
    연산된 결과: view (가상 테이블)
    ‼️
    여러 행을 그룹화하여 단일 값을 반환하는 함수

    1. 그룹함수

    함수
    설명
    예제
    COUNT()
    개수 반환
    SELECT COUNT(*) FROM employees;
    SUM()
    합계 반환
    SELECT SUM(salary) FROM employees;
    AVG()
    평균 반환
    SELECT AVG(salary) FROM employees;
    MAX()
    최댓값 반환
    SELECT MAX(salary) FROM employees;
    MIN()
    최솟값 반환
    SELECT MIN(salary) FROM employees;
    GROUP_CONCAT()
    그룹별 값 연결 (문자열)
    SELECT GROUP_CONCAT(name) FROM employees;

    그룹 연산

    -- 세로 연산 // 옆에 컬럼을 붙일 수 없다 -- 1. 그룹 함수 select avg(height) from student;
    notion image
     
    select count(height) -- row의 개수 from student;
    notion image
     
    select sum(height) from student;
    notion image
     
    select min(height) from student;
    notion image
     
    select max(height) from student;
    notion image
     
    원하는 행만 세로 연산하기
    --75년생 몸무게 평균 select avg(weight) from student where year(birthday) = 1975;
    notion image
     
    -- 정교수들의 연봉평균 select avg(pay) from professor where position = '정교수';
    notion image
     
    -- 정교수들의 연봉평균_반올림 select floor(avg(pay)) from professor where position = '정교수';
    notion image
     

    2. Group by 해서 연산하기

    • 전체 행 세로 연산: sum, max, min, count, avg
    • 특정 행 세로 연산: where과 그룹함수
    • 특정 그룹 세로 연산: where과 그룹함수
    • 그룹별로 세로 연산: group by와 그룹함수
    ‼️
    Group by, Unionall
    -- 3. 그룹핑 하기 // 데이터가 동일하면 그룹핑 가능 select sal , deptno from emp where deptno = 20;
    notion image
     
    select avg(sal) , deptno from emp where deptno = 10;
    notion image
     
    select avg(sal) , deptno from emp where deptno = 20;
    notion image
     
    select avg(sal) , deptno from emp where deptno = 30;
    notion image
     
    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
     
    select avg(sal) , deptno from emp group by deptno;
    notion image
     

    Having

    -- deptno '10' 제거 select job, deptno, avg(sal) from emp group by job, deptno having deptno != 10; -- 그룹핑 된 상태에서 그 결과를 가지고 원하는 행 골라 낼 때
    notion image
    -- 평균 연봉이 2000 이상인 부서는? select avg(sal), deptno from emp group by deptno having avg(sal) > 2000;
    notion image
     

     
    그룹화 과정
    From emp →테이블 퍼올리기
    From emp →테이블 퍼올리기
     
    Group by → DEPTNO 데이터 정렬
    Group by → DEPTNO 데이터 정렬
     
    정렬해서 그룹으로 만든 후 Select avg() → 동일한 DEPTNO끼리 평균 계산
    정렬해서 그룹으로 만든 후 Select avg() → 동일한 DEPTNO끼리 평균 계산
     
     
    Share article
    Contents
    1. 그룹함수 2. Group by 해서 연산하기

    parangdajavous

    RSS·Powered by Inblog